<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/mapping-5000-years-of-city-growth/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://spatial.ly/2017/03/mapping-5000-years-of-city-growth/"> R – Spatial.ly</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>I recently stumbled upon a <a target="_blank" rel="nofollow" href="http://www.nature.com/articles/sdata201634">great dataset</a>. It’s the first to provide comprehensive data for world city sizes as far back as 3700BC. The authors (Meredith Reba, Femke Reitsma &amp; Karen Seto) write:</p>
<p><em>How were cities distributed globally in the past? How many people lived in these cities? How did cities influence their local and regional environments? In order to understand the current era of urbanization, we must understand long-term historical urbanization trends and patterns. However, to date there is no comprehensive record of spatially explicit, historic, city-level population data at the global scale. Here, we developed the first spatially explicit dataset of urban settlements from 3700 BC to AD 2000, by digitizing, transcribing, and geocoding historical, archaeological, and census-based urban population data previously published in tabular form by Chandler and Modelski.</em></p>
<p>These kinds of data are crying out to be mapped so that’s what I did…</p>
<p><img alt="" class="wp-image-5850" src="https://i1.wp.com/spatial.ly/wp-content/uploads/2017/03/city_mollweide.gif?resize=937%2C544" data-recalc-dims="1"></p>
<h2>Creating the Maps</h2>
<p>I was keen to see how easy it was to produce an animated map with R and the ggplot2 package from these data. It turned out to be a slightly bigger job than I thought – partly because the cleaned data doesn’t have all the population estimates updating for every city each year so there’s a bit of a messy loop at the start of the code to get that bit working, and partly because there a LOADS of different parameters to tweak on ggplot to get the maps looking the way I like. The script below will generate a series of PNGs that can be strung together into an animation using a graphics package. I’m a big fan of what ggplot2 can do now and I hope, at the very least, the chunks of ggplot2 code below will provide a useful template for similar mapping projects.</p>
<div>
<h3>R Code</h3>
<p>Load the libraries we need</p>
<pre><code>library(&quot;ggplot2&quot;)
library(&quot;ggthemes&quot;)
library(&quot;rworldmap&quot;)
library(&quot;classInt&quot;)
library(&quot;gridExtra&quot;)
library(&quot;grid&quot;)
library(&quot;cowplot&quot;)</code></pre>
<p>load data – this is the processed file from <a target="_blank" rel="nofollow" href="http://www.nature.com/articles/sdata201634">http://www.nature.com/articles/sdata201634</a> I offer no guarantees about whether I ran the script correctly etc! I’d encourage you to take the data direct from the authors.</p>
<pre><code>#City data
cities&lt;- read.csv(&quot;<a target="_blank" rel="nofollow" href="http://spatial.ly/wp-content/uploads/2017/03/alldata.csv.zip">alldata.csv</a>&quot;)

#for some reason the coords were loaded as factors so I've created two new numeric fields here
cities$X&lt;-as.numeric(as.vector(cities$Longitude))
cities$Y&lt;-as.numeric(as.vector(cities$Latitude))

#World map base from rworldmap
world &lt;- fortify(getMap(resolution=&quot;low&quot;))</code></pre>
<p>Take a look at the data</p>
<pre><code>head(cities)</code></pre>
<p>Create the base map</p>
<pre><code>base&lt;- ggplot() + geom_map(data=world, map=world, aes(x=long,y=lat, map_id=id, group=group),fill=&quot;#CCCCCC&quot;) +theme_map()</code></pre>
<p>Now plot the cities on top – with circles scaled by city size. Here I am using the mollweide projection. This script loops through the data and checks for updates from one year to the next. It then plots the cities as proportional circles for each year and saves out an image for each 100 years of data. If you are just interested in the maps themselves and have your own point data then most of the below can be ignored.</p>
<p>Set the breaks for the size of the circles</p>
<pre><code>size_breaks&lt;-c(10000,50000,100000,500000,1000000,5000000,10000000)</code></pre>
<pre><code>#Here I'm looping through the data each year to select the years required and comparing/ updating the values for each city.
count&lt;-1
for (i in unique(cities$year))
{
if (count==1)
{
  Data&lt;-cities[which(cities$year==i),]
}else{
  New_Data&lt;-cities[which(cities$year==i),]
  #replace old rows
  Data2&lt;-merge(Data, New_Data, by.x=&quot;X&quot;, by.y=&quot;X&quot;, all=T)

  New_Vals&lt;-Data2[!is.na(Data2$pop.y),c(&quot;City.y&quot;,&quot;X&quot;,&quot;Y.y&quot;,&quot;pop.y&quot;)]
  names(New_Vals)&lt;-c(&quot;City&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;pop&quot;)
  
  Old_Vals&lt;-Data2[is.na(Data2$pop.y),c(&quot;City.x&quot;,&quot;X&quot;,&quot;Y.x&quot;,&quot;pop.x&quot;)]
  names(Old_Vals)&lt;-c(&quot;City&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;pop&quot;)

  Data&lt;-rbind(New_Vals,Old_Vals)
  Data&lt;- aggregate(Data$pop, by=list(Data$City,Data$X, Data$Y), FUN=&quot;mean&quot;)
  names(Data)&lt;-c(&quot;City&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;pop&quot;)
}

  
#This statement sorts out the BC/ AC in the title that we'll use for the plot.
if(i&lt;0)
{
title &lt;- paste0(&quot;Cities in the Year &quot;,sqrt(i^2),&quot; BC&quot;)
}else{
  title &lt;- paste0(&quot;Cities in the Year &quot;,i,&quot; AD&quot;)
  
}

#There's lots going on here with the myriad of different ggplot2 parameters. I've broken each chunk up line by line to help make it a little clearer.  
    
Map&lt;-base+
  geom_point(data=Data, aes(x=X, y=Y, size=pop), colour=&quot;#9933CC&quot;,alpha=0.3, pch=20)+
  scale_size(breaks=size_breaks,range=c(2,14), limits=c(min(cities$pop), max(cities$pop)),labels=c(&quot;10K&quot;,&quot;50k&quot;,&quot;100K&quot;,&quot;500k&quot;,&quot;1M&quot;,&quot;5M&quot;,&quot;10M+&quot;))+
  coord_map(&quot;mollweide&quot;, ylim=c(-55,80),xlim=c(-180,180))+
  theme(legend.position=&quot;bottom&quot;,legend.direction=&quot;horizontal&quot;,legend.justification=&quot;center&quot;,legend.title=element_blank(),plot.title = element_text(hjust = 0.5,face='bold',family = &quot;Helvetica&quot;))+ggtitle(title)+guides(size=guide_legend(nrow=1))
 
#I only want to plot map every 100 years
if(i%%100==0)
{
png(paste0(&quot;outputs/&quot;,i,&quot;_moll.png&quot;), width=30,height=20, units=&quot;cm&quot;, res=150)
print(Map)
dev.off()
}
count&lt;-count+1
}</code></pre>
<p>Just to make things a little more interesting I wanted to try a plot of two hemispheres (covering most, but not all) of the globe. I’ve also added the key in between them. This depends on the <code>plot_grid()</code> functionality as well as a few extra steps you’ll spot that we didn’t need above.</p>
<pre><code>count&lt;-1
for (i in unique(cities$year))
{
if (count==1)
{
  Data&lt;-cities[which(cities$year==i),]
}else{
  New_Data&lt;-cities[which(cities$year==i),]
  #replace old rows
  Data2&lt;-merge(Data, New_Data, by.x=&quot;X&quot;, by.y=&quot;X&quot;, all=T)

  New_Vals&lt;-Data2[!is.na(Data2$pop.y),c(&quot;City.y&quot;,&quot;X&quot;,&quot;Y.y&quot;,&quot;pop.y&quot;)]
  names(New_Vals)&lt;-c(&quot;City&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;pop&quot;)
  
  Old_Vals&lt;-Data2[is.na(Data2$pop.y),c(&quot;City.x&quot;,&quot;X&quot;,&quot;Y.x&quot;,&quot;pop.x&quot;)]
  names(Old_Vals)&lt;-c(&quot;City&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;pop&quot;)

  Data&lt;-rbind(New_Vals,Old_Vals)
  Data&lt;- aggregate(Data$pop, by=list(Data$City,Data$X, Data$Y), FUN=&quot;mean&quot;)
  names(Data)&lt;-c(&quot;City&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;pop&quot;)
}

#Create a map for each hemisphere - to help with the positioning I needed to use the `plot.margin` options in the `theme()` settings.
map1&lt;-base+geom_point(data=Data, aes(x=X, y=Y, size=pop), colour=&quot;#9933CC&quot;,alpha=0.3, pch=20)+scale_size(breaks=size_breaks,range=c(2,16), limits=c(min(cities$pop), max(cities$pop)))+coord_map(&quot;ortho&quot;, orientation = c(10, 60, 0),ylim=c(-55,70))+ theme(legend.position=&quot;none&quot;,plot.margin = unit(c(0.5,0.5,-0.1,0.5), &quot;cm&quot;))

map2&lt;- base+geom_point(data=Data, aes(x=X, y=Y, size=pop), colour=&quot;#9933CC&quot;,alpha=0.3, pch=20)+scale_size(breaks=size_breaks,range=c(2,16),limits=c(min(cities$pop), max(cities$pop)))+coord_map(&quot;ortho&quot;, orientation = c(10, -90, 0),ylim=c(-55,70))+ theme(legend.position=&quot;none&quot;, plot.margin = unit(c(0.5,0.5,0,0.5), &quot;cm&quot;))

#create dummy plot that we will use the legend from - basically I just want to create something that has a legend (they've been switched off for the maps above)

dummy&lt;-ggplot()+geom_point(aes(1:7,1,size=size_breaks),colour=&quot;#9933CC&quot;, alpha=0.3, pch=20)+scale_size(breaks=size_breaks,range=c(2,16),labels=c(&quot;10K&quot;,&quot;50k&quot;,&quot;100K&quot;,&quot;500k&quot;,&quot;1M&quot;,&quot;5M&quot;,&quot;10M+&quot;),limits=c(min(cities$pop), max(cities$pop)))+theme(legend.position=&quot;bottom&quot;,legend.direction=&quot;vertical&quot;,legend.title=element_blank())+guides(size=guide_legend(nrow=1,byrow=TRUE))

Legend &lt;- get_legend(dummy)

#This statement sorts out the BC/ AC in the title.

if(i&lt;0)
{
title &lt;- ggdraw() + draw_label(paste0(&quot;Cities in the Year &quot;,sqrt(i^2),&quot; BC&quot;), fontface='bold',fontfamily = &quot;Helvetica&quot;)
}else{
  title &lt;- ggdraw() + draw_label(paste0(&quot;Cities in the Year &quot;,i,&quot; AD&quot;), fontface='bold',fontfamily = &quot;Helvetica&quot;)
  
}
#I only want to plot map every 100 years
if(i%%100==0)
{
png(paste0(&quot;outputs/&quot;,i,&quot;.png&quot;), width=20,height=30, units=&quot;cm&quot;, res=150)
#This is where the elements of the plot are combined
print(plot_grid(title,map1, Legend,map2, ncol=1,rel_heights = c(.1,1, .1,1)))
dev.off()
}
count&lt;-count+1
}</code></pre>
</div>
<p> </p>
<p><img alt="" class="wp-image-5837" src="https://i0.wp.com/spatial.ly/wp-content/uploads/2017/03/city_growth.gif?resize=605%2C1062" data-recalc-dims="1"></p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://spatial.ly/2017/03/mapping-5000-years-of-city-growth/"> R – Spatial.ly</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 title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/YHCSx5aBfPg"></a></div>