Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Notes on mapping sp objects with ggplot2
library(ggplot2)
library(maptools)
library(mapproj)
library(ggthemes)
library(sp)
library(raster)
library(rgeos)
library(RColorBrewer)
# Get administrative boundaries as SpatialPolygonsDataFrame
crc <- raster::getData(name = "GADM", download = TRUE,
path = "data",
country = "CR",
level = 2)
# Crop
new.ext <- raster::extent(c(-86, -82, 8, 11.25))
crc <- raster::crop(crc, new.ext)
# Polygon IDs to merge original SpatialPolygonsDataFrame object with newly
# fortified data.frame.
crc$id <- 1:nrow(crc)
# Fortify SpatialPolygonsDataFrame object for ggplot2
crc.df <- ggplot2::fortify(crc)
# Merge spatial attributes to fortified data.frame
crc.df <- merge(crc.df, crc, by = "id")
# Plot
ggplot(data = crc.df) +
geom_polygon(aes(x = long, y = lat, group = group, fill = NAME_1)) +
geom_path(aes(x = long, y = lat, group = group), colour = "white", size = 0.25) +
scale_fill_brewer(palette = "Set3") +
labs(title = "Costa Rica", fill = "Canton") +
coord_map() +
theme_minimal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment