How to create an election map in R

If you’re mapping election results of, say, the US presidential election by state, it can make sense to just show one color of red for states won by Republicans, and one color of blue for states won by Democrats. That’s because it doesn’t matter whether a candidate wins by three thousand votes or three million: It’s “winner take all.”

But when analyzing results of a state election by county, or a city-wide election by precinct, the margin matters. It’s the overall total that decides the winner. Winning “Atlanta” itself isn’t all you need to know when looking at Georgia statewide results for governor, for example. You’d want to know how many votes the Democrat won by, and compare that to other areas. 

That’s why I like to create maps that are color-coded by winner and with intensity of color showing margin of victory. That tells you which areas contributed more and which contributed less to the overall result.

In this demo, I’ll use Pennsylvania 2016 presidential results. If you’d like to follow along, download the data and geospatial shapefiles:


Election data file and shapefile. Sharon Machlis


I first load some packages: dplyr, glue, scales, htmltools, sf, and leaflet. I’ll use rio to import the data CSV file, so you’ll want that on your system as well.

library(dplyr); library(glue); library(scales); 
library(htmltools); library(sf); library(leaflet)
pa_data <- rio::import("pa_2016_presidential.csv")

Data import and prep

Next, I use sf’s st_read() function to import a shapefile of Pennsylvania counties.

Copyright © 2020 IDG Communications, Inc.

Source link