我使用栅格包中的getData函数来检索阿根廷的地图。我想使用ggplot2绘制生成的地图,所以我使用扫帚包中的整洁函数转换为数据框。这工作正常,但我不知道如何保留联邦区的名称,以便我可以在地图上使用它们。使用扫帚包整理地图时保留区域名称
这里是我的原代码,不保留地区名称:
# Original code: ##################################
# get the map data from GADM.org and then simplify it
arg_map_1 <- raster::getData(country = "ARG", level = 1, path = "./data/") %>%
# simplify
rmapshaper::ms_simplify(keep = 0.01) %>%
# tidy to a dataframe
broom::tidy()
# plot the map
library(ggplot2)
ggplot(data=arg_map_1) +
geom_map(map=arg_map_1, aes(x=long, y=lat, map_id=id, fill=id),
color="#000000", size=0.25)
,这里是用劈拉地区名称了SPDF,并利用它们作为地图标识代码:
# Code with a hack to keep the district names: ################################
# get the map data from GADM.org and then simplify it
arg_map_1 <- raster::getData(country = "ARG", level = 1, path = "./data/") %>%
# simplify
rmapshaper::ms_simplify(keep = 0.01)
for(region_looper in seq_along([email protected]$NAME_1)){
[email protected][[region_looper]]@ID <-
as.character([email protected]$NAME_1[region_looper])
}
# tidy to a dataframe
arg_map_1 <- arg_map_1 %>%
broom::tidy()
library(ggplot2)
ggplot(data=arg_map_1) +
geom_map(map=arg_map_1, aes(x=long, y=lat, map_id=id, fill=id),
color="#000000", size=0.25)
我一直在想,必须有一些方法来使用保留名称的整齐函数,但对于我的生活,我无法弄清楚。
我没有你的数据,但在'扫帚:: sp_tidiers',有一个'region'参数,如果你正在处理一个'SpatialPolygonsDataFrame'。 – alistaire
如果在所提供的路径中未找到数据,'raster :: getData'函数将下载数据。我应该提到我在文档中发现了'region'参数,但我无法弄清楚如何将'arg_map_1 @ data $ NAME_1'的值传递给它。 – jkgrain