How can I share legend for multiple maps in tmap?
Asked Answered
T

1

8

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?

Tessitura answered 26/7, 2018 at 2:14 Comment(0)
P
6

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

Pulmonic answered 2/8, 2018 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.