Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I share legend for multiple maps in tmap?

Tags:

r

tmap

Running example code from tmap library:

library("tmap")
tmap_mode("plot")
data(NLD_muni)

tm_shape(NLD_muni) +
  tm_borders() +
  tm_bubbles(size = c("origin_native", "origin_non_west"), legend.size.is.portrait = TRUE)

Gives me following map

enter image description here

All works as advertised, however I'm trying to force tmap to use same bubble size on both maps.. and plot only one legend. How could that be achieved?

like image 732
radek Avatar asked Jul 26 '18 02:07

radek


1 Answers

Size: You need to specify size.max to give both variables common reference.

Legend: there is no straightforward way -- you cannot pass c(TRUE, FALSE) vector to legend.size.show, it's either both or none. You need to use a workaround with custom grid.

Code below:

library(grid)
library(tmap)
tmap_mode("plot")
data(NLD_muni)

max_size <- max(c(NLD_muni$origin_non_west, NLD_muni$origin_native))

nld_plot_native <- tm_shape(NLD_muni) +
  tm_borders() +
  tm_bubbles(
    size = "origin_native", 
    size.max = max_size, 
    legend.size.is.portrait = TRUE,
    legend.size.show = TRUE
  )

nld_plot_non_west <- tm_shape(NLD_muni) +
  tm_borders() +
  tm_bubbles(
    size = "origin_non_west", 
    size.max = max_size, 
    legend.size.is.portrait = TRUE,
    legend.size.show = FALSE
  )

grid.newpage()
pushViewport(viewport(layout = grid.layout(1, 2)))
print(nld_plot_native, vp = viewport(layout.pos.col = 1))
print(nld_plot_non_west, vp = viewport(layout.pos.col = 2))

enter image description here

like image 135
pieca Avatar answered Oct 10 '22 02:10

pieca