Skip to content

Instantly share code, notes, and snippets.

@sboysel
Created July 29, 2015 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sboysel/f131154a5cda3ca6568e to your computer and use it in GitHub Desktop.
Save sboysel/f131154a5cda3ca6568e to your computer and use it in GitHub Desktop.
# Prepare SpatialPolygonsDataFrame for plotting with ggplot2
# Follows https://github.com/hadley/ggplot2/wiki/plotting-polygon-shapefiles
# Assumes you are in Hadleyverse and already have dplyr loaded.
prepare_spdf <- function(spdf) {
require(dplyr)
reguire(ggplot2)
spdf@data$id <- rownames(spdf@data)
spdf.points <- ggplot2::fortify(spdf, region = "id")
if (sum(is.na(spdf.points$hole))) {
spdf.points <- spdf.points %>%
dplyr::filter(hole == FALSE)
}
spdf.df <- dplyr::left_join(spdf.points, spdf@data, by = "id")
return(spdf.df)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment