How to do it...

In this recipe, we demonstrate how to get a map from the maps package, convert it to a SpatialPolygons object, and then add data from a normal data frame to create a SpatialPolygonsDataFrame object, which we then plot. To do this, follow these steps:

  1. Load the packages needed:
> library(maps) 
> library(maptools) # this also loads the sp package 
  1. Get the county map of New Jersey:
> nj.map <- map("county", "new jersey", fill=TRUE, plot=FALSE) > str(nj.map) List of 4 $ x : num [1:774] -75 -74.9 -74.9 -74.7 -74.7 ... $ y : num [1:774] 39.5 39.6 39.6 39.7 39.7 ... $ range: num [1:4] -75.6 -73.9 38.9 41.4 $ names: chr [1:21] "new jersey,atlantic" "new jersey,bergen" "new jersey,burlington" "new jersey,camden" ... - attr(*, "class")= ...

Get R Data Analysis Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.