我使用柵格包中的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