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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.