Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R tmap, how do I control layer visibility in interactive mode?

Tags:

r

tmap

Starting with a toy example I can quickly get an interactive map in tmap with the following code:

library(tmap)
tmap_mode("view")

data("World", "metro")

tm_shape(World) +
  tm_polygons() +
  tm_shape(metro) +
  tm_dots("pop2010", 
          col = "red") + 
  tm_format("World")

I'd like the map to initially display only the World layer and have the metro layer hidden. It'd only appear when user ticks the box in the layers selection.

I went through tm_shape and tm_dots docs and haven't found anything that seems to control such behaviour. Is that possible?


1 Answers

Seems that this was addressed on GitHub as an issue here as well.

One solution would be to use tmap::tmap_leaflet() to create a leaflet widget, and then use leaflet::hideGroup to show/hide layers.

library(tmap)
library(leaflet)

tmap_mode("view")

data("World", "metro")

tm <-
  tm_shape(World) +
  tm_polygons() +
  tm_shape(metro) +
  tm_dots("pop2010", 
          col = "red") + 
  tm_format("World")

# Pipe the tmap object into tmap_leaflet() to create a leaflet widget,
# so that we can use leaflet::hideGroup().
tm %>% 
  tmap_leaflet() %>%
  leaflet::hideGroup("metro")
like image 89
Valentin Avatar answered Oct 22 '25 16:10

Valentin