Let’s learn how to use Shapefiles in R. This will allow us to map data for complicated areas or jurisdictions like zipcodes or school districts. For the United States, many shapefiles are available from the Census Bureau. Our example will map U.S. national parks.
First, download the U.S. Parks and Protected Lands shape files from Natural Earth. We’ll be using the ne_10m_parks_and_protected_lands_area.shp file.
Next, start working in R. First, we’ll load the shapefile and maptools:
# load up area shape file:
area <- readShapePoly("ne_10m_parks_and_protected_lands_area.shp")
# # or file.choose:
# area <- readShapePoly(file.choose())
Next we can set the colors we want to use. And then we can set up our basemap.
colors <- brewer.pal(9, "BuGn")
mapImage <- get_map(location = c(lon = -118, lat = 37.5),
color = "color",
source = "osm",
# maptype = "terrain",
zoom = 6)
Next, we can use the fortify function from the ggplot2 package. This converts the crazy shape file with all its nested attributes into a data frame that ggmap will know what to do with.
area.points <- fortify(area)
Finally, we can map our shape files!
geom_polygon(aes(x = long,
y = lat,
group = group),
data = area.points,
color = colors,
fill = colors,
alpha = 0.5) +
labs(x = "Longitude",
y = "Latitude")
|National Parks and Protected Lands in California and Nevada|
|Same figure, with a Stamen terrain basemap with ColorBrewer palette “RdPu”|
The full code is available as a gist.