I am using the getData function from the raster package to retrieve the map of Argentina. I would like to plot the resulting map using ggplot2, so I am converting to a dataframe using the tidy function from the broom package. This works fine, but I can't figure out how to preserve the names of the federal districts so that I can use them on the map.
Here is my original code that does not preserve the district names:
# 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)
And here is the code with a hack to pull the district names out of the SPDF and use them as the map IDs:
# 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(arg_map_1@data$NAME_1)){
arg_map_1@polygons[[region_looper]]@ID <-
as.character(arg_map_1@data$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)
I keep thinking that there must be some way to use the tidy function that preserves the names, but for the life of me, I can't figure it out.