County level choropleth of the US Presidential Elections Results (2016)

. 2 min read

The historic election victory of Mr. Trump will be a motivator of posts by data analysts for quite sometime! Here is my attempt to replicate the choropleth shown in this Economist Daily Chart on country divided by counties.

As a side note, Many thanks to Ari Lamstein for his various posts and packages to help beginner analysts like me to produce fairly good analyses and visualizations.

Inspecting the link in Chrome Dev tools gave me access to the dataset which appears practically read to analyze! The dataset made available here for reproduction purposes.

The dataset shows the margin of victory displayed by the cat field.

US Elections Dataset

Meant to represent the "category" as shown in this original screenshot below:

US presidential election results by county, 2016 - Original

I'll attempt to replicate this chart using the Ari's packages. My goal is to make a near replica of it (and I've made few cleanup to hack together a valid set as accuracy isn't my primary goal here!).

Also, the dataset contains the history for a lot of years (yay!) but I will analyze this only for 2016 shown by year = 17

My code is as follows. I load some frequently used packages but don't necessarily use all of them here.

require("data.table")
require("RJSONIO")

library('readr')
library('choroplethr')
library('choroplethrMaps')
library('ggplot2')
library('ggthemes')
library('RColorBrewer')
library('gridExtra')
library('dplyr')
library('stringr')
library('tidyr')


d <- read.csv("data-files/election-data_10-11-2016.csv")
dt <- as.data.table(d)
dt_2016 <- dt[year == 17]
dt_results <- dt_2016


data("county.regions")
dt_county_regions <- as.data.table(county.regions)
dt_county_regions[,fips:=region]

setkeyv(dt_results, c("fips"))
setkeyv(dt_county_regions, c("fips"))

dt_results <- merge(dt_results, dt_county_regions, all.x=TRUE, all.y=TRUE)
dt_results <- dt_results[!is.na(region)]
dt_results <- dt_results[!is.na(cat)]


dt_results[,value:=as.factor(as.integer(cat))]

library(RColorBrewer)
myColors <- c(sort(brewer.pal(4,"Blues")), brewer.pal(5,"Reds"))

choro = CountyChoropleth$new(dt_results)
choro$title = "Democrat vs. Republican distribution in the US Presidential Election (2016)"
choro$ggplot_scale = scale_fill_manual(name="category", values=myColors, drop=FALSE)
choro$render()

The output here:

County Choropleth of 2016 US Election Results using R

Close huh!? :-) (again .. not fully accurate)

An animation across years can be made using the same data which I'll save for another time! :-)


Tags

AWS Analytics Antifragile Apache Spark Apple Apps Arbitrage Automation Awesome BBMP Bangalore Black Swan Bonds Boonex Bootstrap Brokerage Charges CFPB CMS CSS Calypso Camelot Capital Markets Charts Chirp Choropleth Chrome Code Igniter Collections Containerization Converters Cycling DalalBeat Data Analytics Data Journalism Data Mining Data Munging Data Privacy Data Science Databases Debt Design Design Stock DesignStock Diet Django Docker Document Processing Dropbox Electron Electronics Entertainment Entrepreneurship Exercise FFMPEG Facebook Finance Fire TV Stick Fitness Forerunner From-The-News Fun Futures Gaana Garmin General Geocoding Getting Started Ghost Google APIs GraphicsMagick HHVM HTTPS Hackathon Hacks Hardware Health House Keeping Housing IBM BlueMix IBrokers IPinfo Ideas Image Conversion Image Processing Infographics Interactive Brokers Internet Investing IoT Legal Lets Encrypt Mac Machine Learning Mailbox app Mapbox Markdown Marketing Meteor Mockups MongoDB Mortgages Movies Music MyPad MySQL Nativefier Nature Netflix Newsletters Nginx Node.js Notes OCR OSX Open Source OpenCPU Options PDF PHP Pebble Peloton Personal Photography Picture Platforms Plex Portable Apps Productivity Property Tax PyroCMS Quantitative Finance R-Project Random Raspberry Pi Research Resources Reticulate Robot S3 SQLite STT Scraping Security Server Shell Shiny Side Project Sikuli Speech Recognition Spider Pro Spinning Spotify Startup Resources Startups Strategy Sublime Text System Monitoring Tax Terminal Tips To Do Tools Torrent Trading Trends Troubleshooting USElection2016 Ubuntu Unix Valuations Video Conversion Visualization Wagtail Wearables Weekend Fun WhatsApp Wordpress anaconda annie bash catalina cv2 daily coding dailycoding data.table debugging devtools downloader e-Signatures ggplot git go google maps hat-tip iOS iPad iPhone iTunes javascript jupyter logging macos numpy opencv optionality plotly python rstats videos youtube