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.
Sharon Machlis, IDG Map of 2016 Pennsylvania US presidential election results color-coded by party of the county victor and margin of victory. The interactive version lets you mouse over (tap on mobile) to see underlying data.
Map of 2016 Pennsylvania US presidential election results color-coded by party of the county victor and margin of victory. The interactive version lets you mouse over (tap on mobile) to see underlying data.
Philadelphia is at the bottom right. You can see just how important it is, population-wise, compared to all other areas of Pennsylvania that are large on the map but have far fewer voters.
It might be interesting to map the difference in raw vote margins between one election and another, such as Pennsylvania in 2016 vs. 2020. That map would show where patterns shifted the most and might help explain changes in statewide results.
If you are interested in more election data visualizations, I have made an . You can either install it as-is or and tailor it for your own use.
For more R tips, head to .
Copyright © 2020 IDG Communications, Inc.