<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/animated-great-circles-on-rotating-3d-earth-example-r-code/"></div></div><div><a data-url="http://www.r-bloggers.com/animated-great-circles-on-rotating-3d-earth-example-r-code/" data-counturl="http://www.r-bloggers.com/animated-great-circles-on-rotating-3d-earth-example-r-code/" data-count="horizontal" data-text="Animated great circles on rotating 3D Earth: Example R code" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://blog.snap.uaf.edu/2016/05/16/animated-great-circles-on-rotating-3d-earth-example-r-code/"> rbloggers – SNAP Tech</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<h1>Making still frames for great circle animations in R</h1>
<p>Matthew Leonawicz</p>
<p>Here I share R code I used to produce <a target="_blank" href="https://www.youtube.com/watch?v=uQYR91qixgo">animated great circle arcs</a> on top of a rotating 3D Earth. The code is not entirely reproducible but you should be able to use what is shared here to create your own video frames given your unique data and computing environment and resources.</p>
<p><iframe height="400" width="450" allowfullscreen="true" src="https://www.youtube.com/embed/uQYR91qixgo?version=3&rel=1&%23038;fs=1&%23038;autohide=2&%23038;showsearch=0&%23038;showinfo=1&%23038;iv_load_policy=1&%23038;wmode=transparent" type="text/html"></iframe></p>
<p><em>The WordPress blog is not the most elegant for displaying lots of code so go to the <a target="_blank" href="http://leonawicz.github.io/gc_animation_example/app_traffic_example.html">original full post</a>.</em></p>
<p>When I make great circle animations, at the core of the process is always an R function that transforms a series of coordinates describing points along a great circle arc into multiple series of great circle arc segments. The goal is simple: plot a series of line segments, saving each plot as a subsequent still frame, rather than plotting the original entire arc as a single plot. The input is generally a data table (much faster to work with than a data frame if you have a lot of data) with longitude and latitude columns where the coordinates in each row describe a subsequent point along one of my paths. I also use a third column to provide a unique group ID for each path to keep them distinct.</p>
<p><span></span></p>
<p>Before getting to this process, here is some example code of how I formatted my data this way when using the <code>geosphere</code> package. Do not get bogged down in the details here. This is just an example for fuller context regarding my specific animation referenced above and I will not be focusing on it. Your data will be quite different. You will have to arrange it similarly, but obviously it will be in a different context.</p>
<h3>Data prep example</h3>
<p>As you can see below, all you need is a data frame with columns of longitude and latitude. I created a <code>SpatialPoints</code> object from these. In my case I wanted to connect great circle arcs between each of two specific locations and all other locations in my data set. I marked the row indices for these two locations.</p>
<pre>
library(dplyr)
library(geosphere)

load(&quot;data.RData&quot;)  # a data frame, d, containing 'long' and 'lat' columns
p &lt;- SpatialPoints(cbind(d$long, d$lat), proj4string = CRS(&quot;+proj=longlat +datum=WGS84&quot;))
idx1 &lt;- 69  # great circles from coords in all other rows to coords in this row
idx2 &lt;- 2648  # as above

get_paths &lt;- function(x, idx, ...) {
    gcInt &lt;- function(x, x1, x2) {
        x &lt;- gcIntermediate(x[x1, ], x[x2, ], ...)
        if (is.list(x)) {
            x &lt;- x %>% purrr::map2(c(x1, x1 + 0.5), ~data.frame(.x, .y)) %>% 
                bind_rows %>% setnames(c(&quot;long&quot;, &quot;lat&quot;, &quot;group&quot;))
        } else x &lt;- data.frame(x, x1) %>% setnames(c(&quot;long&quot;, &quot;lat&quot;, &quot;group&quot;))
        x
    }
    purrr::map(setdiff(1:length(x), idx), ~gcInt(x, .x, idx)) %>% bind_rows
}

paths1 &lt;- get_paths(p, idx1, addStartEnd = TRUE)
paths2 &lt;- get_paths(p, idx2, addStartEnd = TRUE)
</pre>
<p><code>get_paths</code> uses <code>gcIntermediate</code> from the <code>geosphere</code> package to obtain vectors of points defining great circle arcs between my two locations and all others. The resulting data frame has columns, <code>long</code>, <code>lat</code>, and <code>group</code>. I do not break the arcs at the dateline because I intend to draw them on a 3D globe, but if I were making a flat map I would do so. This is why the function handles the case of list output from <code>gcIntermediate</code> and adjusts the group ID by add 0.5 to one group.</p>
<p>Already more than enough details. You can see what I am going for though. Given my data, I want to end up with columns of longitude and latitude defining great circle arcs and broken out by unique group IDs. I show this because it's highly likely you will want to use <code>geosphere</code> in a similar way even if you won't be connecting points in the same way I am here.</p>
<h3>Transforming great circle arcs into segments</h3>
<p>Okay. You have your data in the right format. Now you want to break up your groups of great circle arcs into a larger number of nested subgroups of great circle arc segments. Let's get some basic prep out of the way.<br>
Here are the packages I am using.</p>
<h4>The steup</h4>
<pre>
library(parallel)
library(gridExtra)
library(raster)
library(data.table)
library(dplyr)
library(ggplot2)

eb &lt;- element_blank()
theme_blank &lt;- theme(axis.line = eb, axis.text.x = eb, axis.text.y = eb, axis.ticks = eb, 
    axis.title.x = eb, axis.title.y = eb, legend.position = &quot;none&quot;, panel.background = eb, 
    panel.border = eb, panel.grid.major = eb, panel.grid.minor = eb, plot.background = element_rect(colour = &quot;transparent&quot;, 
        fill = &quot;transparent&quot;))

world &lt;- map_data(&quot;world&quot;)
</pre>
<p>The <code>ggplot2</code> theme will allow for plotting without all the extraneous stuff like margins and axes and colors I don't want on my Earth. The world map is an aside and has nothing to do with the great circles. I include it here because it was part of my animation. It will be used from plotting the backdrop of nation boundaries on the globe. Having these underneath the great circle animation is helpful for geographic visual orientation.</p>
<p>It's not clear yet, but the reason for including the <code>raster</code> package is because I also use a rasterized map layer of the earth's surface as the bottom layer underneath the nation boundaries. This is also an aside. It doesn't have anything to do with the great circle animation.</p>
<p>Yes, I am using R's built-in <code>parallel</code> package. I happen to be do at least the parallelized operations in this project on a Linux server with 32 CPUs and 260 GB RAM. I'm sorry to say but I can't help you if you want to do this on a local Windows pc for example. If you rework the code for a much more restrictive environment, depending on your data, you may find yourself waiting forever for your output. I just do not recommend doing this type of thing outside of a beefy server environment, at least if time is something you value.</p>
<p>Now, getting to the core of the process for real this time. Here is the actual function I used for the above animation to break great circle arcs into smaller segments.</p>
<h4>The main function</h4>
<pre>
df_segs &lt;- function(d, seg.size, n.frames, replicates = 1, direction = &quot;fixed&quot;) {
    n &lt;- nrow(d)
    if (n &lt; 3) 
        stop(&quot;Data not appropriate for this operation.&quot;)
    if (seg.size &lt; 3) 
        stop(&quot;Segment size too small.&quot;)
    z &lt;- round(runif(2, 2, seg.size))
    z[z > n] &lt;- n
    n1 &lt;- ceiling(diff(c((z[1] - z[2]), n))/z[1])
    if (n.frames - n1 &lt; 100) 
        stop(&quot;Insufficient frames&quot;)
    offset &lt;- sample(0:(n.frames - n1), replicates)
    
    f &lt;- function(k, d, n, n1, z, offset) {
        ind2 &lt;- z[1] * k
        ind1 &lt;- max(ind2 - z[2], 1)
        if (ind2 > n) 
            ind2 &lt;- n
        d &lt;- slice(d, ind1:ind2)
        purrr::map(offset, ~mutate(d, group = ifelse(replicates == 1, group, 
            group + as.numeric(sprintf(&quot;.%d&quot;, k))), frameID = .x + k)) %>% bind_rows
    }
    
    if (direction == &quot;reverse&quot;) 
        d &lt;- mutate(d, long = rev(long), lat = rev(lat))
    if (direction == &quot;random&quot; &amp;&amp; rnorm(1) &lt; 0) 
        d &lt;- mutate(d, long = rev(long), lat = rev(lat))
    d &lt;- purrr::map(1:n1, ~f(.x, d, n, n1, z, offset)) %>% bind_rows %>% arrange(group, 
        frameID)
    d
}
</pre>
<p>Going through the code, you can see it requires a minimum of 100 desired frames (which would make for quite a short video). You can tweak the maximum number of points in a segment. The minimum is always two. Each segment will vary in length uniformly between the minimum and maximum.</p>
<p>You can leave the data as is, with <code>direction=&quot;fixed&quot;</code>. This assumes the ordering of points/rows pertaining to each group is intended to show direction. Segments will be assembled in the same order. Alternatively, you can reverse or even randomize the order if it doesn’t matter for the given data.</p>
<p>This is just one example function. You can make your own if this one does not generate the type of segments or provide the kind of random variation in segments you would like.</p>
<p>Let’s go with 900 frames, which will result in about a 30 second video. Recall that in my case I had two different data sets. I combine them at the end of the above code snippet.</p>
<pre>
n.frames &lt;- 900
set.seed(1)
paths2 &lt;- mutate(paths2, group = group + max(paths1$group))
paths &lt;- bind_rows(paths1, paths2) %>% split(.$group)
</pre>
<p>Here I make the new table below. It has a subgroup ID column as well as a frame ID column. Group ID is now a decimal. To the left is the original great circle ID. To the right is the sequential segment ID. The latter is random and not all great circle arcs are broken up into the same number of segments. Some cover more rows of the table than others. They do not match up with the frame IDs and some recycling may be required if the number of desired frames is large enough.</p>
<pre>
paths &lt;- mclapply(paths, df_segs, seg.size = 5, n.frames = n.frames, replicates = 1, 
    direction = &quot;random&quot;, mc.cores = 32) %>% bind_rows
</pre>
<p>Alternatively, code like this will perform the same operation without using parallel processing. This may not be terribly problematic if the data set is not too large. I show this for comparison. But the need for parallel will be much greater in later steps.</p>
<pre>
paths &lt;- paths %>% split(.$group) %>% purrr::map(~df_segs(.x, 5, n.frames, replicates = 1, 
    direction = &quot;random&quot;)) %>% bind_rows
</pre>
<h3>Aside: the background layer<a target="_blank" href="https://uasnap.files.wordpress.com/2016/05/tile.png"><img height="300" alt="tile" width="300" class="wp-image-1328" src="https://uasnap.files.wordpress.com/2016/05/tile.png?w=300&h=300"></a></h3>
<h4>Where I got the data</h4>
<p>I use a rasterized bathymetry surface based on a csv file I downloaded by using the <code>marmap</code> package. I won’t discuss that here. Please see the <code>marmap</code> package for details and examples if this is important. It is straightforward to use that package to download a local copy of a subregion of the data (or the whole map) at a specified resolution.</p>
<h4>Projecting background layer to 3D</h4>
<p>The <code>project_to_hemisphere</code> function below (adapted from <code>mapproj</code> <a target="_blank" href="http://stackoverflow.com/questions/35911452/clipping-polygons-when-drawing-world-map-in-orthographic-projection">here</a>) projects points onto the 3D earth and identifies which ones are within the hemisphere field of view given the centroid focal point. Identifying the half which are out of view in any given frame allows me to toss them out for some added efficiency. This is not actually a slow process. The conversion of coordinates is not complex or demanding. The slow part is drawing the high resolution orthographic projection maps with <code>ggplot2</code>.</p>
<pre>
d.bath &lt;- read.csv(&quot;marmap_coord_-180;-90;180;90_res_10.csv&quot;) %>% data.table %>% 
    setnames(c(&quot;long&quot;, &quot;lat&quot;, &quot;z&quot;))
r &lt;- raster(extent(-180, 180, -90, 90), res = 1/6)
projection(r) &lt;- &quot;+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs&quot;
r &lt;- setValues(r, d.bath$z)
</pre>
<pre>
project_to_hemisphere &lt;- function(lat, long, lat0, long0) {
    hold &lt;- c(lat, long)
    x &lt;- (pi/180) * c(lat, lat0, long - long0)
    inview &lt;- sin(x[1]) * sin(x[2]) + cos(x[1]) * cos(x[2]) * cos(x[3]) > 0
    data.table(long = hold[2], lat = hold[1], inview = inview)
}
</pre>
<h3>Prepare for plotting</h3>
<p>I want a 120-frame period, which is about four seconds of video, in which time I will complete one rotation of the earth. I define a sequence of longitude values, but this I allow to repeat for the total number of video frames, <code>n.frames</code>, specified earlier. Note that I keep the latitude focus (41 degrees) constant in this animation, but there is no reason this cannot vary as well. In the <code>save_maps</code> function below, there is a hard-coded 23.4-degree fixed orientation, but this is something that can also be made variable.</p>
<p>While the data we are interested in – the great circle arc segments – will plot sequentially over a series of 900 frames, both the nation boundaries and bathymetry surface map backdrops are constant so I only need to produce enough frames (120) for one rotation of each of those layers.</p>
<p>I split the path segments table on the frame ID. I will generate still frames in parallel.</p>
<p>In this animation I had originally chosen to aggregate my 10-minute resolution bathymetry surface from the <code>marmap</code> package because that resolution was a bit too fine and even in parallel it was taking an extremely long time for <code>ggplot2</code> to draw the orthographic projection background maps. If I understand correctly, it is drawing a ton of tiny, filled polygons. It really grinds to a halt if you have a massive amount of them.</p>
<h4>Some setup</h4>
<pre>
n.period &lt;- 120
lon_seq &lt;- rep(seq(0, 360, length.out = n.period + 1)[-(n.period + 1)], length = n.frames)
lat_seq &lt;- rep(41, length(lon_seq))
paths &lt;- paths %>% split(.$frameID)
d.bath.agg &lt;- r %>% aggregate(2) %>% rasterToPoints %>% data.table %>% setnames(c(&quot;long&quot;, 
    &quot;lat&quot;, &quot;z&quot;))
</pre>
<p>Next, in parallel across frames, I project my rasterized background map cells to the 3D surface and retain only the ones which are in view in a given frame as the earth spins. I use the full range of elevation data to retain a constant color palette mapping as cells at different extreme elevations move in and out of the field of view as the earth rotates. I store the range in <code>z.range</code>. I add a frame ID column. Finally I add a frame ID column for the nation boundaries table. The data is constant, but simply needs to be plotted 120 times in 3-degree shifts.</p>
<pre>
d.tiles &lt;- mclapply(1:n.period, function(i, x, lon, lat) {
    left_join(x, project_to_hemisphere(x$lat, x$long, lat[i], lon[i])) %>% filter(inview) %>% 
        dplyr::select(-inview) %>% mutate(frameID = i)
}, x = d.bath.agg, lat = lat_seq, lon = lon_seq, mc.cores = 32)

z.range &lt;- purrr::map(d.tiles, ~range(.x$z, na.rm = TRUE)) %>% unlist %>% range
d.world &lt;- purrr::map(1:n.period, ~mutate(world, frameID = .x))
</pre>
<h3>Save plots</h3>
<p>I've showed the most important of two functions for making my great circle animation, <code>df_segs</code>, which I use to transformed a table of grouped rows of great circle arc coordinates into a much larger one with nested, grouped, sequential arc segments. The other critical function is <code>save_maps</code>.</p>
<p>Here I have generalized it a bit by adding a <code>type</code> argument. It is primarily used for iterating over the data for each frame in a table produced by <code>df_segs</code> (the default <code>type=&quot;network&quot;</code>). This saves a map image of sequential great circle arc segments for each frame.</p>
<p>I added the options, <code>type=&quot;maplines&quot;</code> and <code>type=&quot;maptiles&quot;</code>. The former is for the nation boundaries and the latter is for the rasterized map surface.</p>
<p>I call the function in parallel three times to cover each type of output. I generate 120 frames (one earth rotation in three-degree increments) of both the nation boundaries and the surface tiles. The latter takes by far the longest amount of time to process, far longer than even the 900 frames of network traffic itself.</p>
<h4>The other main function</h4>
<pre>
save_maps &lt;- function(x, lon_seq, lat_seq, col = NULL, type = &quot;network&quot;, z.range = NULL) {
    if (is.null(col)) 
        col &lt;- switch(type, network = c(&quot;#FFFFFF25&quot;, &quot;#1E90FF25&quot;, &quot;#FFFFFF&quot;, 
            &quot;#1E90FF50&quot;), maptiles = c(&quot;black&quot;, &quot;steelblue4&quot;), maplines = &quot;white&quot;)
    i &lt;- x$frameID[1]
    if (type == &quot;network&quot;) 
        x.lead &lt;- group_by(x, group) %>% slice(n())
    g &lt;- ggplot(x, aes(long, lat))
    if (type == &quot;maptiles&quot;) {
        if (is.null(z.range)) 
            z.range &lt;- range(x$z, na.rm = TRUE)
        g &lt;- ggplot(x, aes(long, lat, fill = z)) + geom_tile() + scale_fill_gradientn(colors = col, 
            limits = z.range)
    } else {
        g &lt;- ggplot(x, aes(long, lat, group = group))
        if (type == &quot;maplines&quot;) 
            g &lt;- g + geom_path(colour = col)
        if (type == &quot;network&quot;) 
            g &lt;- g + geom_path(colour = col[2]) + geom_path(colour = col[1]) + 
                geom_point(data = x.lead, colour = col[3], size = 0.6) + geom_point(data = x.lead, 
                colour = col[4], size = 0.3)
    }
    g &lt;- g + theme_blank + coord_map(&quot;ortho&quot;, orientation = c(lat_seq[i], lon_seq[i], 
        23.4))
    dir.create(outDir &lt;- file.path(&quot;frames&quot;, type), recursive = TRUE, showWarnings = FALSE)
    png(sprintf(paste0(outDir, &quot;/&quot;, type, &quot;_%03d.png&quot;), i), width = 4 * 1920, 
        height = 4 * 1080, res = 300, bg = &quot;transparent&quot;)
    print(g)
    dev.off()
    NULL
}

mclapply(paths, save_maps, lon_seq, lat_seq, type = &quot;network&quot;, mc.cores = 30)
mclapply(d.world, save_maps, lon_seq, lat_seq, type = &quot;maplines&quot;, mc.cores = 30)
mclapply(d.tiles, save_maps, lon_seq, lat_seq, type = &quot;maptiles&quot;, z.range = z.range, 
    mc.cores = 30)
</pre>
<h3>What about the video?</h3>
<p>For any project like this I simply drop each of the three sequences of sequentially numbered png files onto its own timeline track as a still image sequence in a standard video editor. I don't use R for this final step. While I could have plotted everything together on a single sequence of frames, it doesn't make sense to do so even when each sequence has equal length. This is because one sequence may take far longer to plot than another sequence. It is more efficient to make a different image sequence for separate layers and mix them in the editor afterward.</p>
<p>You might also notice the very high pixel dimensions of the png outputs. I do this in cases where I plan to zoom during an animation. The larger the image, the more I can zoom in without degradation. You can imagine that this generates a lot of data when you have thousands of frames and each image is several megabytes.</p>
<h3>Conclusion: Don't try this at home</h3>
<p>Instead, try something like this on a server with plenty of CPUs and RAM. Otherwise try it with a small data set. Due to the particular computing environment I used and the resources needed to process the frames in an efficient and timely fashion, it is impossible to share this example animation code in a completely reproducible fashion. However, you should be able to use <code>df_segs</code> or some alteration of it with a properly formatted input table to generate the type of table you would want to pass subsequently to <code>save_maps</code> (or some alteration of that as well).</p>
<p>That is the gist of this example and should be enough to get you started. Ultimately, you will have to adapt any code here to your unique data, its size and complexity, what exactly you want to do with it, and your available computing resources.</p>
<p><img height="1" alt="" width="1" src="https://pixel.wp.com/b.gif?host=blog.snap.uaf.edu&blog=35883776&%23038;post=1325&%23038;subd=uasnap&%23038;ref=&%23038;feed=1" border="0"></p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/animated-great-circles-on-rotating-3d-earth-example-r-code/"></div></div><div><a data-url="http://www.r-bloggers.com/animated-great-circles-on-rotating-3d-earth-example-r-code/" data-counturl="http://www.r-bloggers.com/animated-great-circles-on-rotating-3d-earth-example-r-code/" data-count="vertical" data-text="Animated great circles on rotating 3D Earth: Example R code" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://blog.snap.uaf.edu/2016/05/16/animated-great-circles-on-rotating-3d-earth-example-r-code/"> rbloggers – SNAP Tech</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Y205lq0pGgw"></a></div>