我正在尝试使用 tmap 包在 R 中绘制一个交互式地图。
我有一个多边形形状,其中包含不同年份的数据。当我每年使用它时tm_shape() + tm_fill()
,它会自动为每年制作一张新的单独地图。
我想在一张交互式地图中绘制多个图层。这样,通过在左侧的下拉菜单中选择不同的图层,您可以看到多年来的变化。
有谁知道这是否可能以及如何做到这一点?
这是我的脚本:
require(rgdal)
require(tidyverse)
require(tmap)
require(tmaptools)
# files
download.file("https://www.haarlem.nl/bestandsopslag/bestanden/Opendata/Veiligheid_-_Misdrijven.csv", "veiligheid_misdrijven_haarlem.csv")
download.file("https://www.cbs.nl/-/media/_pdf/2016/35/shape%202014%20versie%2030.zip", "buurten.zip")
unzip("buurten.zip")
# read shape (Haarlem)
shape <- readOGR("uitvoer_shape",layer=ogrListLayers("uitvoer_shape")[1])[4546:4585,]
# change projection
shape <- spTransform(shape, CRS("+proj=sterea +lat_0=52.15616055555555
+lon_0=5.38763888888889 +k=0.999908
+x_0=155000 +y_0=463000 +ellps=bessel
+units=m +towgs84=565.2369,50.0087,
465.658,-0.406857330322398,0.350732676542563,
-1.8703473836068,4.0812 +no_defs"))
# read data
data <- as.tibble(read.table("veiligheid_misdrijven_haarlem.csv",
header=TRUE, sep=";", dec=",",
skip = 4, nrows = 40, stringsAsFactors = FALSE))
# clean data
data <- data %>%
separate(X, into = c("buurt", "nummer", "name"), sep = c(6,10)) %>%
select(-buurt, -nummer) %>%
arrange(name)
# bind data to shape
shape@data <- cbind(arrange(shape@data,BU_NAAM), data)
# plot interactive map
tmap_mode("view")
tm_shape(shape) +
tm_borders(alpha=0.5) +
tm_fill(c("X2000","X2013"), style="quantile", alpha=.5,
palette=colorRampPalette(c("white", "red"))(5),
popup.vars = c("name","X2000","X2013") ) +
tm_scale_bar()