Thursday, February 28, 2013

Shapefiles in R

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!

ggmap(mapImage) +
  geom_polygon(aes(x = long,
      y = lat,
      group = group),
    data = area.points,
    color = colors[9],
    fill = colors[6],
    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.

Citations and Further Reading


  1. This comment has been removed by the author.

  2. Mollie thank you so much for your kind explanation. I would like to ask you if you can explain me how to paint each polygon with different color. Thank you in advance

  3. I could, sorry for the inconveniences :p

  4. Hello and thank you very much for posting this. It has been very useful. One question: when I zoom in a specific area, the polygons does not form nice shapes. It's like it only draws shapes that can be seen in the window. I hope you understand what I mean, otherwise I can clearify it further. Do you know how to handle this problem? /Peter

  5. how can I display the same map on google online map?
    Is there any way to do the same?
    I have to display the shape file on google dynamic(online map) not in a static map(it is like an image)?