O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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")= ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required