In my last post, I displayed a series of maps from the 2014 Massachusetts midterm election. In all, I created 17 maps, all with fewer than 20 lines of code. Here’s how…

The basic idea is to use a For Loop with ggmap to iterate through columns of a data frame. In my example, the code for which can be found here, I first read shapefiles from MassGIS into R, and then combine them with election data. The rationale for these steps can be seen in Hadley’s excellent shapefile tutorial.

# First prepare the parcel df mass <- readOGR(dsn="./shapefiles", layer="GISDATA_CENSUS2010TOWNS_POLY") mass@data$id = rownames(mass@data) names(mass) mass.points <- fortify(mass, region="id") mass.df <- join(mass.points, mass@data, by="id") # Prepare data to match with MassGis layer d$TOWN <- toupper(d$Municipality) # Combine data mass.df <- merge(mass.df, d, by="TOWN") # Map map <- get_map(location = "Grafton, Massachusetts", zoom=8, maptype="roadmap", color = "bw") ggmap(map)

Now we have merged election data to the shapefile and prepared a Google base map in black and white that is focused on Grafton, MA (which happens to be close to the center of Massachusetts). Next, we will use this to make multiple choropleth maps of the election data.