<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/the-world-population-is-changing/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://nowosad.github.io/post/world-pop-change/"> 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>Last month, <a rel="nofollow" href="https://twitter.com/MaxCRoser" target="_blank">Max Roser</a> presented a <a rel="nofollow" href="https://ourworldindata.org/wp-content/uploads/2018/09/Population-cartogram_World-1.png" target="_blank">cartogram</a> of the Earth’s population in 2018.<br>
He also provided some perspectives on its spatial distribution in an article on the <a rel="nofollow" href="https://ourworldindata.org/world-population-cartogram" target="_blank">worldinourdata.org</a>, which I recommend.<br>
Links to the article were shared in many places, including in the blog post <a rel="nofollow" href="https://kottke.org/18/09/a-map-of-the-world-where-the-sizes-of-countries-are-determined-by-population" target="_blank">A Map of the World Where the Sizes of Countries Are Determined by Population</a>.<br>
The author, <a rel="nofollow" href="https://twitter.com/jkottke" target="_blank">Jason Kottke</a>, concluded with a wish:</p>
<blockquote>
<p>“I would love to see an animated version of this cartogram from like 1950 to 2100”.</p>
</blockquote>
<p>Why not from 1800 to 2100?<br>
And why not do it using open data and open source software, so that anyone can reproduce the results?<br>
That is the aim of this post.<br>
In it, we will see how to generate the animated cartogram illustrated below.</p>
<div>
<img alt="Animated cartogram of the world population changes between 1800 and 2100." src="https://i1.wp.com/nowosad.github.io/post/2018-10-09-world_pop_change_files/world_pop_1800_2100.gif?w=456&ssl=1" data-recalc-dims="1">
<p>Animated cartogram of the world population changes between 1800 and 2100.</p>
</div>
<p>The above animation was created using open data (from <a rel="nofollow" href="https://www.gapminder.org/" target="_blank">gapminder.org</a>) and open source software (R, which can be downloaded from <a rel="nofollow" href="https://cloud.r-project.org/" target="_blank">r-project.org</a>).<br>
This means not only that you can reproduce the results.<br>
You can also change (for example to create yearly changes instead of changes every 25 years) and potentially improve them.</p>
<p>Described in the book <a rel="nofollow" href="https://geocompr.robinlovelace.net/" target="_blank">Geocomputation with R</a>, which helped inspire this post, this is how open source software works: someone writes code that does something useful and the community contributes to make it even better (see the source code of this post <a rel="nofollow" href="https://nowosad.github.io/post/world-pop-change/" target="_blank">here</a>).</p>
<p>The rest of this post is more focused on the code.<br>
I will explain how the steps involved in making the above animation, and, in the final section, link to more comprehensive teaching material that will teach not only how to make a multitude of other types of maps in R, but also how to ensure the results are reproducible.</p>
<p>The first stage is to prepare the data.</p>
<div>
<h2>Prepare</h2>
<p>Let’s start with the packages.<br>
If you are new to R, you may want to take a read of <a rel="nofollow" href="https://geocompr.robinlovelace.net/spatial-class.html" target="_blank">this</a> first, which points to various resources for setting-up R for geographic data.<br>
When you have a recent R version and the appropriate packages installed (e.g. by executing <code>devtools::install_github(&quot;geocompr/geocompkg&quot;)</code>) the packages can be attached as follows:</p>
<pre><code>library(sf)             # spatial data classes
library(rnaturalearth)  # world map data
library(readxl)         # reading excel files
library(dplyr)          # data manipulation
library(tidyr)          # data manipulation
library(purrr)          # data manipulation
library(cartogram)      # cartograms creation
library(tmap)           # maps creation</code></pre>
</div>
<div>
<h2>Data</h2>
<p>To create cartograms of the world population for each year we will need two datasets – one containing spatial data of the world’s countries and one non-spatial with information about the annual population in the world’s countries.<br>
The first one can be easily downloaded from the <a rel="nofollow" href="http://www.naturalearthdata.com/" target="_blank">Natural Earth</a> website, for example using the <strong>rnaturalearth</strong> package:</p>
<pre><code>world_map = ne_countries(returnclass = &quot;sf&quot;)</code></pre>
<p>The second one is available from the <a rel="nofollow" href="https://www.gapminder.org/" target="_blank">Gapminder</a> foundation.<br>
Gapminder provides <a rel="nofollow" href="https://www.gapminder.org/data/documentation/gd003/" target="_blank">a dataset with population data</a> for all countries and world regions from 1800 to 2100.<br>
We can download and read the dataset using the code below:</p>
<pre><code>if(!dir.exists(&quot;data&quot;)) dir.create(&quot;data&quot;)
download.file(&quot;http://gapm.io/dl_pop&quot;, destfile = &quot;data/pop1800_2100.xlsx&quot;)
world_pop = read_xlsx(&quot;data/pop1800_2100.xlsx&quot;, sheet = 7)</code></pre>
</div>
<div>
<h2>Cleaning</h2>
<p>As always when working with multiple datasets – some data cleaning will be necessary.<br>
Our <code>world_map</code> dataset has many columns unnecessary for cartograms creation and we do not need spatial data of Antarctica.<br>
Let’s get rid of them.<br>
we can also transform our data into a more appropriate projection<a rel="nofollow" href="https://nowosad.github.io/post/world-pop-change/#fn1" target="_blank"><sup>1</sup></a>.</p>
<pre><code>world_map = world_map %>% 
  select(sovereignt) %>% 
  filter(sovereignt != &quot;Antarctica&quot;) %>% 
  st_transform(world_map, crs = &quot;+proj=robin&quot;)</code></pre>
<p>We need to have a common identifier to combine our spatial and non-spatial datasets, for example, names of the countries.<br>
However, there are inconsistencies between some of the names.<br>
We need to fix it manually:</p>
<pre><code>world_pop = world_pop %>% 
  mutate(sovereignt = name) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Tanzania&quot;, &quot;United Republic of Tanzania&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;United States&quot;, &quot;United States of America&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Congo, Dem. Rep.&quot;, &quot;Democratic Republic of the Congo&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Bahamas&quot;, &quot;The Bahamas&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Serbia&quot;, &quot;Republic of Serbia&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Macedonia, FYR&quot;, &quot;Macedonia&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Slovak Republic&quot;, &quot;Slovakia&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Czech Republic&quot;, &quot;Czechia&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Congo, Rep.&quot;, &quot;Republic of the Congo&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Kyrgyz Republic&quot;, &quot;Kyrgyzstan&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Lao&quot;, &quot;Laos&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Swaziland&quot;, &quot;eSwatini&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Cote d'Ivoire&quot;, &quot;Ivory Coast&quot;)) %>% 
  mutate(sovereignt = replace(sovereignt, sovereignt == &quot;Timor-Leste&quot;, &quot;East Timor&quot;))</code></pre>
</div>
<div>
<h2>Preparing</h2>
<p>Now we can join our two datasets, remove missing values and unimportant columns.<br>
We also should transform the data into a long format<a rel="nofollow" href="https://nowosad.github.io/post/world-pop-change/#fn2" target="_blank"><sup>2</sup></a> accepted by the <strong>tmap</strong> package.</p>
<pre><code>world_data = left_join(world_map, world_pop, by = &quot;sovereignt&quot;) %>% 
  na.omit() %>% 
  select(-geo, -name, -indicator) %>% 
  gather(key = &quot;year&quot;, value = &quot;population&quot;, `1800.0`:`2100.0`) %>% 
  mutate(year = as.integer(year)) </code></pre>
<p>Additionally, we can calculate total global populations in each year:</p>
<pre><code>world_data = world_data %>% 
  group_by(year) %>% 
  mutate(total_pop = sum(as.numeric(population), na.rm = TRUE)) %>% 
  mutate(title = paste0(&quot;Year: &quot;, year, &quot;\nTotal population (mln): &quot;, round(total_pop/1e6, 2)))</code></pre>
</div>
<div>
<h2>Subset</h2>
<p>Now, our data contains information about the world population for each year between 1800 and 2100.<br>
It is possible to use it to create cartograms, however, to reduce calculation time and simplification of the results we will only use data for every 25 years:</p>
<pre><code>world_data = world_data %>% 
  filter(year %in% seq(1800, 2100, by = 25))</code></pre>
</div>
<div>
<h2>Transforming</h2>
<p>Finally, we are able to create our cartograms.<br>
We need to split our data into independent annual datasets, create cartograms based on the <code>population</code> variable, and combine all of the cartograms back into one object.</p>
<p>Before we create cartograms of the world, let’s create a single cartogram:</p>
<pre><code>world_data_2100 = world_data %>%
  filter(year == 2100)
world_carto1 = cartogram_cont(world_data_2100, &quot;population&quot;, maxSizeError = 1.5)
plot(world_carto1[&quot;population&quot;])</code></pre>
<div>
<img alt="A single cartogram of year 2100." src="https://i1.wp.com/nowosad.github.io/post/2018-10-09-world_pop_change_files/world_carto1.png?w=456&ssl=1" data-recalc-dims="1">
<p>A single cartogram of year 2100.</p>
</div>
<p>The resulting plot was with the awesome <strong>sf</strong> package, showing what global populations could look like based on recent trends.<br>
To make this animated, we need to a) do some more processing (to calculate the cartogram shapes for every year in our sequence) and b) switch to using the awesome <strong>tmap</strong> package for animated map creation.<br>
Note: this next step may take a few minutes.</p>
<pre><code># warning: this may make your computer's fan spin!
world_data_carto = world_data %>% 
  split(.$year) %>%
  map(cartogram_cont, &quot;population&quot;, maxSizeError = 1.5) %>% 
  do.call(rbind, .) </code></pre>
</div>
<div>
<h2>Visualizing</h2>
<p>Animated maps can be created in a single command using the <strong>tmap</strong> package.<br>
Below we pass it the data produced in the previous command:</p>
<pre><code>carto_anim = tm_shape(world_data_carto) +
  tm_polygons(&quot;population&quot;, title = &quot;Population: &quot;) +
  tm_facets(along = &quot;title&quot;, free.coords = FALSE, drop.units = TRUE)</code></pre>
<p>The last step is to save the output object as a .gif file:</p>
<pre><code>tmap_animation(carto_anim, filename = &quot;world_pop_1800_2100.gif&quot;, delay = 75,
               width = 1326, height = 942)</code></pre>
<p>If you enjoyed this tutorial you’re in luck: there’s lots more to learn!<br>
In addition to chapters on a range of fundamental geographic subjects, there’s an entire chapter on visualization in the online version of <strong>Geocomputation with R</strong>, which can be found at <a rel="nofollow" href="https://geocompr.robinlovelace.net/" target="_blank">https://geocompr.robinlovelace.net/</a> (the physical book will be on sale soon).</p>
</div>
<div>
<h2>Epilogue</h2>
<p>There are several things that should be kept in mind about this animation.<br>
Firstly, the animation (as well the Gapminder data) shows the world as if all countries always had the borders they have today.<br>
This is, of course, untrue, but this simplification allows for the straightforward creation of the animation as well as for an easier understanding of the results.<br>
Secondly, the most time-consuming part of the animation creation, constructing continuous area cartograms, can be accelerated, with the use of simplified geometries of the world countries (for example using the <strong>rmapshaper</strong> package) or with parallel processing (for example using the <strong>future</strong> or <strong>furrr</strong> packages).<br>
Thirdly, different time steps can be used – an animation could be created for each year, every five years, etc.<br>
And finally, cartograms can be animated using a different R package, for example,<strong>gganimate</strong>, or even combine into an interactive app using <strong>shiny</strong>.</p>
</div>
<div>
<hr>
<ol>
<li>
<p>You can read more about projections in the <a rel="nofollow" href="https://geocompr.robinlovelace.net/reproj-geo-data.html" target="_blank">Reprojecting geographic data</a> chapter of Geocomputation with R.<a rel="nofollow" href="https://nowosad.github.io/post/world-pop-change/#fnref1" target="_blank"><img alt="↩" src="https://s.w.org/images/core/emoji/2.4/72x72/21a9.png" class="wp-smiley"></a></p>
</li>
<li>
<p>This process is called <a rel="nofollow" href="http://r4ds.had.co.nz/tidy-data.html#gathering" target="_blank">gathering</a>.<a rel="nofollow" href="https://nowosad.github.io/post/world-pop-change/#fnref2" target="_blank"><img alt="↩" src="https://s.w.org/images/core/emoji/2.4/72x72/21a9.png" class="wp-smiley"></a></p>
</li>
</ol>
</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/world-pop-change/"> 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/ktELhSrwNTc" height="1"></a></div>