Created
June 17, 2016 16:01
-
-
Save sboysel/3398f4108f72df7b72f9f7d844768ae9 to your computer and use it in GitHub Desktop.
Notes on mapping sp objects with ggplot2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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