<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/subplots-in-maps-with-ggplot2/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://ikashnitsky.github.io/2017/subplots-in-maps/"> Ilya Kashnitsky</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Following the <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/images/170525/prev-post-success.png">surprising success</a> of <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/2017/align-six-maps/">my latest post</a>, I decided to show yet another use case of the handy <code>ggplot2::annotation_custom()</code>. Here I will show how to add small graphical information to maps – just like putting a stamp on an envelope.</p>
<p>The example comes from my current work on a paper, in which I study the effect of urban/rural differences on the relative differences in population ageing (I plan to tell a bit more in one of the next posts). Let’s have a look at the map we are going to reproduce in this post:</p>
<p><a target="_blank" rel="nofollow" href="https://i2.wp.com/ikashnitsky.github.io/images/170525/map.png?ssl=1"><img alt="fig1" src="https://i2.wp.com/ikashnitsky.github.io/images/170525/map.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<p>So, with this map I want to show the location of more and less urbanized NUTS-2 regions of Europe. But I also want to show – with subplots – how I defined the three subregions of Europe (Eastern, Southern, and Western) and what is the relative frequency of the three categories of regions (Predominantly Rural, Intermediate, and Predominantly Rural) within each of the subregions. The logic of actions is simple: first prepare all the components, then assemble them in a composite plot. Let’s go!</p>
<p>The code to prepare R session and load the data.</p>
<div>
<pre><code># additional packages
library(tidyverse)
library(ggthemes)
library(rgdal)
library(viridis)
library(extrafont)
myfont &lt;- &quot;Roboto Condensed&quot;

# load the already prepared data
load(url(&quot;https://ikashnitsky.github.io/doc/misc/map-subplots/df-27-261-urb-rur.RData&quot;))
load(url(&quot;https://ikashnitsky.github.io/doc/misc/map-subplots/spatial-27-261.RData&quot;))
</code></pre>
</div>
<p>Now, I prepare the spatial objects to be plotted with ggplot2 and create a blank map of Europe – our canvas.</p>
<div>
<pre><code># fortify spatial objects
bord &lt;- fortify(Sborders)
fort &lt;- fortify(Sn2, region = &quot;id&quot;)

# join spatial and statistical data
fort_map &lt;- left_join(df,fort,&quot;id&quot;)

# create a blank map
basemap &lt;- ggplot()+
        geom_polygon(data = fortify(Sneighbors),aes(x = long, y = lat, group = group),
                     fill = &quot;grey90&quot;,color = &quot;grey90&quot;)+
        coord_equal(ylim = c(1350000,5450000), xlim = c(2500000, 6600000))+
        theme_map(base_family = myfont)+
        theme(panel.border = element_rect(color = &quot;black&quot;,size = .5,fill = NA),
              legend.position = c(1, 1),
              legend.justification = c(1, 1),
              legend.background = element_rect(colour = NA, fill = NA),
              legend.title = element_text(size = 15),
              legend.text = element_text(size = 15))+
        scale_x_continuous(expand = c(0,0)) +
        scale_y_continuous(expand = c(0,0)) +
        labs(x = NULL, y = NULL)
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i2.wp.com/ikashnitsky.github.io/images/170525/basemap.png?ssl=1"><img alt="fig2" src="https://i2.wp.com/ikashnitsky.github.io/images/170525/basemap.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<p>Okay, now the envelope is ready. It’s time to prepare the stamps. Let’s create a nice mosaic plot showing the distribution of NUTS-2 regions by subregions and the urb/rur categories. I found the simplest way to create a nice mosaic plot on <a target="_blank" rel="nofollow" href="http://stackoverflow.com/a/19252389/4638884">Stack Overflow</a>.</p>
<div>
<pre><code># create a nice mosaic plot; solution from SO:
# http://stackoverflow.com/a/19252389/4638884
makeplot_mosaic &lt;- function(data, x, y, ...){
        xvar &lt;- deparse(substitute(x))
        yvar &lt;- deparse(substitute(y))
        mydata &lt;- data[c(xvar, yvar)];
        mytable &lt;- table(mydata);
        widths &lt;- c(0, cumsum(apply(mytable, 1, sum)));
        heights &lt;- apply(mytable, 1, function(x){c(0, cumsum(x/sum(x)))});
        
        alldata &lt;- data.frame();
        allnames &lt;- data.frame();
        for(i in 1:nrow(mytable)){
                for(j in 1:ncol(mytable)){
                        alldata &lt;- rbind(alldata, c(widths[i], 
                                                    widths[i+1], 
                                                    heights[j, i], 
                                                    heights[j+1, i]));
                }
        }
        colnames(alldata) &lt;- c(&quot;xmin&quot;, &quot;xmax&quot;, &quot;ymin&quot;, &quot;ymax&quot;)
        
        alldata[[xvar]] &lt;- rep(dimnames(mytable)[[1]], 
                               rep(ncol(mytable), nrow(mytable)));
        alldata[[yvar]] &lt;- rep(dimnames(mytable)[[2]], nrow(mytable));
        
        ggplot(alldata, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)) + 
                geom_rect(color=&quot;white&quot;, aes_string(fill=yvar)) +
                xlab(paste(xvar, &quot;(count)&quot;)) + 
                ylab(paste(yvar, &quot;(proportion)&quot;));
}

typ_mosaic &lt;- makeplot_mosaic(data = df %>% mutate(type = as.numeric(type)), 
                              x = subregion, y = type)+
        theme_void()+
        scale_fill_viridis(option = &quot;B&quot;, discrete = T, end = .8)+
        scale_y_continuous(limits = c(0, 1.4))+
        annotate(&quot;text&quot;,x = c(27, 82.5, 186), y = 1.05, 
                 label=c(&quot;EAST&quot;, &quot;SOUTH&quot;, &quot;WEST&quot;), 
                 size = 4, fontface = 2, 
                 vjust = 0.5, hjust = 0,
                 family = myfont) + 
        coord_flip()+
        theme(legend.position = &quot;none&quot;)
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i0.wp.com/ikashnitsky.github.io/images/170525/mosaic.png?ssl=1"><img alt="fig3" src="https://i0.wp.com/ikashnitsky.github.io/images/170525/mosaic.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<p>Just what we needed. The next step is to build a small map showing the three subregions of Europe. But before we proceed to the maps, one thing has to be fixed. <code>ggplot2</code> <a target="_blank" rel="nofollow" href="https://stackoverflow.com/questions/21748852">fails rendering nested polygons</a>. With our regional dataset, London, for example, will not be shown if we do not account for this unpleasant feature. Luckily, there is quite a simple <a target="_blank" rel="nofollow" href="https://stackoverflow.com/a/32186989/4638884">solution to fix that problem</a>.</p>
<div>
<pre><code># a nice small function to overcome some mapping problems with nested polygons
# see more at SO
# https://stackoverflow.com/questions/21748852
gghole &lt;- function (fort) {
        poly &lt;- fort[fort$id %in% fort[fort$hole, ]$id, ]
        hole &lt;- fort[!fort$id %in% fort[fort$hole, ]$id, ]
        out &lt;- list(poly, hole)
        names(out) &lt;- c(&quot;poly&quot;, &quot;hole&quot;)
        return(out)
}
</code></pre>
</div>
<p>Now I build the small map of subregions.</p>
<div>
<pre><code># annotate a small map of the subregions of Europe
an_sub &lt;- basemap +
        geom_polygon(data = gghole(fort_map)[[1]], 
                     aes(x = long, y = lat, group = group, fill = subregion),
                     color = NA)+
        geom_polygon(data  =  gghole(fort_map)[[2]], 
                     aes(x = long, y = lat, group = group, fill = subregion),
                     color = NA)+
        scale_fill_manual(values = rev(brbg3)) +
        theme(legend.position = &quot;none&quot;)
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i1.wp.com/ikashnitsky.github.io/images/170525/sub.png?ssl=1"><img alt="fig4" src="https://i1.wp.com/ikashnitsky.github.io/images/170525/sub.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<p>Finally, everything is ready to build the main map and stick the two subplots on top of it.</p>
<div>
<pre><code># finally the map of Urb/Rur typology

caption &lt;- &quot;Classification: De Beer, J., Van Der Gaag, N., &amp; Van Der Erf, R. (2014). New classification of urban and rural NUTS 2 regions in Europe. NIDI Working Papers, 2014/3. Retrieved from http://www.nidi.nl/shared/content/output/papers/nidi-wp-2014-03.pdf
\nIlya Kashnitsky (ikashnitsky.github.io)&quot;

typ &lt;-  basemap + 
        
        geom_polygon(data = gghole(fort_map)[[1]], 
                     aes(x=long, y=lat, group=group, fill=type),
                     color=&quot;grey30&quot;,size=.1)+
        geom_polygon(data = gghole(fort_map)[[2]], 
                     aes(x=long, y=lat, group=group, fill=type),
                     color=&quot;grey30&quot;,size=.1)+
        scale_fill_viridis(&quot;NEUJOBS\ncalssification of\nNUTS-2 regions&quot;, 
                           option = &quot;B&quot;, discrete = T, end = .8)+
        geom_path(data = bord, aes(x = long, y = lat, group = group),
                  color = &quot;grey20&quot;,size = .5) + 
        
        annotation_custom(grob = ggplotGrob(typ_mosaic), 
                          xmin = 2500000, xmax = 4000000, 
                          ymin = 4450000, ymax = 5450000)+
        annotation_custom(grob = ggplotGrob(an_sub), 
                          xmin = 5400000, xmax = 6600000, 
                          ymin = 2950000, ymax = 4150000)+
        labs(title = &quot;Urban / Rural classification of NUTS-2 regions of Europe\n&quot;,
             caption = paste(strwrap(caption, width = 95), collapse = '\n'))+
        theme(plot.title = element_text(size = 20),
              plot.caption = element_text(size = 12))
</code></pre>
</div>
<p><a target="_blank" rel="nofollow" href="https://i2.wp.com/ikashnitsky.github.io/images/170525/map.png?ssl=1"><img alt="fig1" src="https://i2.wp.com/ikashnitsky.github.io/images/170525/map.png?w=456&ssl=1" data-recalc-dims="1"></a></p>
<p>Done!</p>
<p>Of course, it takes several iterations to position each element in its proper place. Then, one also needs to play with export parameters to finally get the desired output.</p>
<h3>The full R script for this post is <a target="_blank" rel="nofollow" href="https://ikashnitsky.github.io/doc/misc/map-subplots/code.R">here</a></h3>
<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://ikashnitsky.github.io/2017/subplots-in-maps/"> Ilya Kashnitsky</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/N2EZYTPV3hY"></a></div>