Last active
January 26, 2022 22:07
-
-
Save lmullen/8375785 to your computer and use it in GitHub Desktop.
How I use shapefiles in R with ggplot2 and RGDAL
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(rgdal) # R wrapper around GDAL/OGR | |
library(ggplot2) # for general plotting | |
library(ggmaps) # for fortifying shapefiles | |
# First read in the shapefile, using the path to the shapefile and the shapefile name minus the | |
# extension as arguments | |
shapefile <- readOGR("path/to/shapefile/", "name_of_shapefile") | |
# Next the shapefile has to be converted to a dataframe for use in ggplot2 | |
shapefile_df <- fortify(shapefile) | |
# Now the shapefile can be plotted as either a geom_path or a geom_polygon. | |
# Paths handle clipping better. Polygons can be filled. | |
# You need the aesthetics long, lat, and group. | |
map <- ggplot() + | |
geom_path(data = shapefile_df, | |
aes(x = long, y = lat, group = group), | |
color = 'gray', fill = 'white', size = .2) | |
print(map) | |
# Using the ggplot2 function coord_map will make things look better and it will also let you change | |
# the projection. But sometimes with large shapefiles it makes everything blow up. | |
map_projected <- map + | |
coord_map() | |
print(map_projected) |
Thanks!
Thanks. Fortify did the trick for me
I think "ggmaps" is now "ggmap"
It seems as if broom::tidy() is becoming the preferred method of converting shapefiles to dataframes.
The function description has changed to:
Rather than using this function, I now recommend using the broom package, which implements a much wider range of methods. fortify may be deprecated in the future.
is it possible to read from github directly? ie i have r script and shapefile/geodatabase all on github, how can i connect them?
Hi. when using the converted shapefile the map appears distorted, how can I solve it?
They know how to color each province according to the prevalence of something, with plot me it was much easier. Thank you
Thanks a lot! fortify is the best
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fortify did the trick!