I'm trying to plot the boundary of different spatialPolygonsDataFrames in ggplot2 or in rasterVis gplot(), but I just can't find the way, they tend to overwrite the previous one; this is something quite common in mapping, having different symbols for each layer, it's something like this what I'm trying to achieve (done with base graphics)

enter image description here

mex <- raster::getData(country="MEX", level=1)
munis <- raster::getData(country="MEX", level=2)
plot(munis[munis$NAME_1=="Veracruz"|munis$NAME_1=="Oaxaca",], border="green")
plot(mex[mex$NAME_1=="Veracruz"|mex$NAME_1=="Oaxaca",], add=T, lty=1)
legend("topright", c("state boundary", "munic. boundary"), pch=14, col=c("black", "green"), bty="n")

1 Answer 1


Here is an alternative using sf package:

# load libraries including development version of ggplot2, which is installed from GitHub (devtools::install_github('tidyverse/ggplot2'))

mex <- raster::getData(country="MEX", level=1)
munis <- raster::getData(country="MEX", level=2) 

# convert to sf object
mex <- st_as_sf(mex) 
munis <- st_as_sf(munis) 

# subset states
mex <- mex[mex$NAME_1 %in% c("Veracruz", "Oaxaca"), ] 
munis <- munis[munis$NAME_1 %in% c("Veracruz", "Oaxaca"), ]

# plot with ggplot 
gp <- ggplot() +
  geom_sf(data = munis, aes(color = 'A'), fill = 'white', show.legend = 'line') +
  geom_sf(data = mex, aes(color = 'B'), lwd = 0.5, fill = 'transparent', show.legend = 'line') +
  scale_color_manual(values = c("A" = "green", "B" = "black"), 
                     labels = c("Municipal Boundary", "State Boundary"),
                     name = NULL) +
  theme(legend.position = c(0.75, 0.8))

# these datasets are large, so I found it is best to save to png rather than trying to load in graphics device to view

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.