I am trying to draw multiple maps from the tmap-package using tm_shape() and tm_layout() in one page using grid.layout() from the grid-package. I would like to plot only one common legend for all maps, similar to the example shown here:
ggplot separate legend and plot
Unfortunately, tmap does not provide a ggplot-object. Does anybody know how to do the same with tmaps? Here is a reproducible example:
data(World, rivers, metro)
# creating two separate maps
africa <- World[World@data$continent=='Africa',]
asia <- World[World@data$continent=='Asia',]
my.breaks <- seq(0,80,20)
africa.map <- tm_shape(africa) +
tm_fill("HPI",style = 'fixed',breaks = my.breaks) +
tm_layout(bg.color = "white", legend.text.size = 1.3, legend.width = 0.6,
legend.outside=TRUE, legend.outside.position = 'top',
legend.outside.size = .1, legend.position = c(0.8, 0.2))
asia.map <- tm_shape(asia) +
tm_fill("HPI",style = 'fixed',breaks = my.breaks) +
tm_layout(bg.color = "white", legend.text.size = 1.3, legend.width = 0.6,
legend.outside=TRUE, legend.outside.position = 'top',
legend.outside.size = .1, legend.position = c(0.8, 0.2))
page.layout <- grid.layout(nrow = 8, ncol = 5,
widths = unit(c(1), "null"),
heights = unit(c(1), "null"),
default.units = "null",
respect = FALSE,
just = "centre")
grid.newpage()
pushViewport(viewport(layout = page.layout))
grid.text(paste('Happy Planet Index'),
vp = viewport(layout.pos.row = 1, layout.pos.col = 1:5),gp=gpar(fontsize=20))
grid.text('Africa', vp = viewport(layout.pos.row = 2, layout.pos.col = 1:2),gp=gpar(fontsize=20))
print(africa.map, vp=viewport(layout.pos.row = 3:6, layout.pos.col = 1:2))
grid.text('Asia', vp = viewport(layout.pos.row = 2, layout.pos.col = 3:5),gp=gpar(fontsize=20))
print(asia.map, vp=viewport(layout.pos.row = 3:6, layout.pos.col = 3:5))
Best, Erich