Creating a Basic Choropleth From a Shapefile in R

A choropleth is a thematic map where areas are colored according to some characteristic of those areas. This is an example of a choropleth commonly seen in news reports that shows the party that won the electoral college votes from different states in a presidential election.

2012 Electoral College Results

The following script creates a basic choropleth equivalent to the one shown above.

A zipped election data shapefile is available here. A shapefile is a a file format for storing geospatial data that was originally developed by ESRI in the 1990s. It is misnamed since a single shapefile actually contains multiple files (.shp, .dbf, .prj, etc.) that store various aspects of the single conceptual geospatial data set. You must unzip this file into its separate parts before you can import it into R using the readOGR() function.

library(rgdal)

# Import state polygons
states = readOGR(dsn=".", layer="2017-state-data", stringsAsFactors=F)

# Select only the contiguous 48 states
states = states[!(states$ST %in% c("AK", "HI")),]

# Reproject to a more realistic North America Albers Equal Area Conic projection
usa_albers = CRS("+proj=aea +lat_1=20 +lat_2=60 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs")
states = spTransform(states, usa_albers)

# Color based on 2012 winner
palette = c("#000080", "#a00000")
colors = ifelse(states$WIN2012 == "Obama", palette[1], palette[2])

# Plot
plot(states, col = colors)

# Add a legend
legend(x = "bottomleft", legend=c("Obama", "Romney"),
	fill=palette, title="2012 Electoral College", bg="white")

To create a PNG file you can insert into a document, place a png() call before the plot() and legend(), and close the file with dev.off():

png(filename="2012-presidential-states.png", width=600, height=400, pointsize=12)

plot(states, col = colors)

legend(x = "bottomleft", legend=c("Obama", "Romney"),
	fill=palette, title="2012 Electoral College", bg="white")

dev.off()