首页 > 解决方案 > 在 R tmap 中,如何在交互模式下控制图层可见性?

问题描述

tmap从一个玩具示例开始,我可以使用以下代码快速获取交互式地图:

library(tmap)
tmap_mode("view")

data("World", "metro")

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

我希望地图最初只显示World图层并隐藏地铁图层。它只会在用户勾选图层选择中的框时出现。

我浏览了文档tm_shapetm_dots没有发现任何似乎可以控制这种行为的东西。那可能吗?

标签: rtmap

解决方案


似乎这在 GitHub 上也作为一个问题在这里得到了解决。

一种解决方案是使用tmap::tmap_leaflet()创建传单小部件,然后使用leaflet::hideGroup显示/隐藏图层

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")

推荐阅读