<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/life-expectancy-animated/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://nowosad.github.io/post/life-expectancy-animated/"> Rstats on Jakub Nowosad's website</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Global socio-economic data is easily accessible nowadays.<br>
Just type the indicator of interest and the name of the country in your preferred search engine and you can find its value, sometimes also an additional plot or a map.<br>
But what about when you want to go further and (for example):</p>
<ul>
<li>Want to compare many countries?</li>
<li>Get data just for a specific year?</li>
<li>See changes in time?</li>
<li>Just want to create a very specific plot or a map?</li>
</ul>
<p>In this blog post, I will show how to download, process, and present global socio-economic data, using the following packages:</p>
<pre><code>library(wbstats) # the World Bank data downloading
library(dplyr) # data manipulation 
library(tidyr) # data manipulation 
library(purrr) # data manipulation 
library(ggplot2) # data visualization 
library(sf) # spatial data manipulation
library(rnaturalearth) # access to spatial data
library(tmap) # spatial data visualization</code></pre>
<div>
<h2>World Bank Data</h2>
<p>The World Bank Data is a source of various global socio-economic indicators with a large database of historical records.<br>
Its API is, for instance, accessible through the R package <strong>wbstats</strong> package.<br>
The two most important functions of this package are <code>wbsearch()</code> and <code>wb()</code>.<br>
The first one allows for searching for available indicators, and the second one is used for downloading the data.<br>
Read <a rel="nofollow" href="https://cran.r-project.org/web/packages/wbstats/README.html" target="_blank">the vignette “wbstats: An R package for searching and downloading data from the World Bank API”</a> to learn more about this package.</p>
<p>Here, I would like to create a time-series of a selected indicator.<br>
The function below downloads data for a given indicator and a year.<br>
Secondly, it selects only the variables of interest and reshapes them into the wide format.</p>
<pre><code>wb_data_create = function(indicator, new_name, year, ...){
  df = wb(indicator = indicator,
          startdate = year, enddate = year, ...) %>%
    select(iso_a2 = iso2c, value, year = date) %>%
    mutate(indicator = new_name) %>%
    spread(indicator, value) %>%
    as_data_frame()
  # return the dataframe
  df
}</code></pre>
<p>Importantly, this function can be also used to download data from many years using the <code>map_dfr()</code> function.<br>
As an example, let’s download a data of life expectancy at birth for every five years from 1963 to 2013 on a country level:</p>
<pre><code>data_life_exp = seq(1963, 2013, by = 5) %>%
  map_dfr(wb_data_create,
          indicator = &quot;SP.DYN.LE00.IN&quot;,
          new_name = &quot;life_exp&quot;,
          country = &quot;countries_only&quot;)</code></pre>
<p>This new dataset, <code>data_life_exp</code>, already allows analyzing temporal changes in life expectancy.<br>
For example, we can calculate the mean life expectancy of all countries:</p>
<pre><code>data_life_exp_avg = data_life_exp %>% 
  group_by(year) %>% 
  summarise(mean_life_exp = mean(life_exp, na.rm = TRUE))</code></pre>
<p>Let’s visualize the life expectancy.<br>
Each grey line represents one country, and the red one shows the mean life expectancy.</p>
<pre><code>ggplot() +
  geom_line(data = data_life_exp, 
            aes(year, life_exp, group = iso_a2), 
            color = &quot;gray40&quot;) + 
  geom_line(data = data_life_exp_avg,
            aes(year, mean_life_exp, group = 1),
            color = &quot;red&quot;, size = 2) +
  labs(x = &quot;Year&quot;, y = &quot;Life expectancy&quot;) + 
  theme_minimal()</code></pre>
<p><img src="https://i1.wp.com/nowosad.github.io/post/2018-07-05-life-expectancy-animated_files/figure-html/unnamed-chunk-5-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
</div>
<div>
<h2>Spatialize it</h2>
<p>Overall, we can see a stable increase in life expectancy over the last 55 years.<br>
However, are there any differences between countries?<br>
What is the spatial distribution of the life expectancy?<br>
To answer that, we can download spatial data of the world using the <strong>rnaturalearth</strong> package:</p>
<pre><code>world = ne_countries(returnclass = &quot;sf&quot;) %>% 
  select(iso_a2, name_long, continent)</code></pre>
<p>Next, we need to combine the new spatial data with our non-spatial information of life expectancy.<br>
First, the non-spatial data is reshaped into the wide form.<br>
This way we are filling missing data with <code>NA</code> instead of removing them<br>
As a result, we will have the same number of countries (borders) for each year in our database.<br>
Secondly, we are joining the spatial <code>world</code> dataset with the non-spatial <code>data_life_exp_wide</code> using the variable <code>&quot;iso_a2&quot;</code> common to both datasets.<br>
The last step is to convert the data back into a long form, where each pair of country and year corresponds to one row.<br>
This also means that the spatial geometry for each country will be repeated for each time step.</p>
<pre><code>data_life_exp_wide = data_life_exp %>% 
  spread(year, life_exp)
world_temporal = world %>%
  left_join(data_life_exp_wide, by = c(&quot;iso_a2&quot;)) %>% 
  gather(year, life_exp, `1963`:`2013`)</code></pre>
</div>
<div>
<h2>Facet map</h2>
<p>How to create a map showing temporal changes?<br>
One of the most straigforward ways is to use a facet plot:</p>
<pre><code>my_map = tm_shape(world_temporal, projection = &quot;robin&quot;) + 
  tm_fill(&quot;life_exp&quot;, title = &quot;Life expectancy&quot;,
          palette = &quot;viridis&quot;) +
  tm_facets(by = &quot;year&quot;, ncol = 3)
my_map</code></pre>
<p><img src="https://i1.wp.com/nowosad.github.io/post/2018-07-05-life-expectancy-animated_files/figure-html/unnamed-chunk-8-1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Each map facet represents a different year.<br>
We can see that, on overall, the map colors shift from darker to more bright, indicating an increase in life expectancy.<br>
There is a noticeable spatial similarity (“spatial autocorrelation”) – European countries tend to have a longer life expectancy, while the lowest life expectancy is in Africa.<br>
This visualization also reveals (or just helps to see) a lot more, for example, life expectancy in China increased visibly faster than in neighboring countries or that there are missing values for Greenland before 1978.</p>
<p>There is, however, a downside of facet maps – each facet is relatively small and it is hard to see any details without zooming in.<br>
Alternatively, an animated map can be created, where each facet would be a next image frame.</p>
</div>
<div>
<h2>Animated map</h2>
<p>The code to create an animated map is almost identical to the facet map code.<br>
There is only one important difference – the <code>along</code> parameter should be used instead of <code>by</code>:</p>
<pre><code>my_ani = tm_shape(world_temporal, projection = &quot;robin&quot;) +
  tm_fill(&quot;life_exp&quot;, title = &quot;Life expectation&quot;,
          palette = &quot;viridis&quot;) +
  tm_facets(along = &quot;year&quot;)</code></pre>
<p>The output, <code>my_ani</code>, is a set of maps – one map per year.<br>
It can be further converted into a proper animation with the <code>tmap_animation()</code> function:</p>
<pre><code>tmap_animation(my_ani, filename = &quot;life_exp_animation.gif&quot;,
               width = 1500, height = 600, delay = 60)</code></pre>
<p><img src="https://i2.wp.com/nowosad.github.io/post/2018-07-05-life-expectancy-animated_files/life_exp_animation.gif?w=456&ssl=1" data-recalc-dims="1"></p>
<p>The output presents the animated changes in life expectancy.<br>
The overall trend is still visible, but also small changes can be seen.<br>
It includes, for example, decreases in life expectancy in Cambodia in the 1970s and Rwanda in the 1990s.</p>
</div>
<div>
<h2>Bonus</h2>
<p>It is also possible to combine the two above methods – facet and animated map.<br>
Let’s try it on the data from South America:</p>
<pre><code>world_temporal_sa = filter(world_temporal,
                           continent == &quot;South America&quot;) %>% 
  na.omit()</code></pre>
<p>To enable animated facet map, both arguments – <code>by</code> and <code>along</code> need to be set.<br>
Here, countries will be presented on facets and each animation frame is a different year.<br>
Feel free to test what would happen if you switch the arguments of <code>by</code> and <code>along</code>.</p>
<pre><code>my_ani2 = tm_shape(world_temporal_sa) +
  tm_polygons(&quot;life_exp&quot;, title = &quot;Life expectation&quot;,
          palette = &quot;viridis&quot;) +
  tm_facets(by = &quot;name_long&quot;, along = &quot;year&quot;, nrow = 3)
tmap_animation(my_ani2, filename = &quot;life_exp_sa_animation.gif&quot;,
               width = 1600, height = 1000, delay = 60)</code></pre>
<p><img src="https://i1.wp.com/nowosad.github.io/post/2018-07-05-life-expectancy-animated_files/life_exp_sa_animation.gif?w=456&ssl=1" data-recalc-dims="1"></p>
<p>This way of presentation has a nice property – it allows for focus on values, instead of countries location or size.<br>
You can easily see values of the smallest countries and compare them to the largest ones.</p>
<p>I must admit that the bonus visualization example might not be the most appropriate.<br>
This visualization method is the best suited for comparing continuous features.<br>
For example, imagine animated facet maps comparing continuous surface phenomena (e.g. temperature or air quality) for each country through time.<br>
Try this method for yourself!</p>
</div>
<div>
<h2>Final words</h2>
<p>This blog post builds on the content in Chapter <a rel="nofollow" href="http://geocompr.robinlovelace.net/adv-map.html#inset-maps" target="_blank">8</a> of the book <strong>Geocomputation with R</strong>.<br>
To learn more about spatial data analysis, visualization and modeling using R visit the online version of the <strong>Geocomputation with R</strong> book at <a rel="nofollow" href="https://geocompr.robinlovelace.net/" target="_blank">https://geocompr.robinlovelace.net/</a>.</p>
</div>
<div>
<h2>Acknowledgement</h2>
<p>I’d like to thanks to Tal Galili (creator of <a rel="nofollow" href="https://www.r-bloggers.com/" target="_blank">https://www.r-bloggers.com/</a> and <a rel="nofollow" href="https://www.r-users.com/" target="_blank">https://www.r-users.com/</a>), and Maëlle Salmon, Bruce Zhao, Colin Fay, Eric Nantz, Hao Zhu, Jasmine Dumas, Jon Calder, Jonathan Carroll, Kun Ren, Tracy Shen, Wolfram Qin (team members of <a rel="nofollow" href="https://rweekly.org/" target="_blank">https://rweekly.org</a>) for doing a great work of gathering and spreading blog posts, tutorials, and many other R-related resources. Keep your awesome work!</p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://nowosad.github.io/post/life-expectancy-animated/"> Rstats on Jakub Nowosad's website</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/YTY7rVGF7GY" height="1"></a></div>