user319487
user319487

Reputation:

How can I share legend for multiple maps in 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?

Upvotes: 8

Views: 1995

Answers (1)

pieca
pieca

Reputation: 2563

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

Upvotes: 6

Related Questions