Tim Thoughts data/rstats/policy

Election Mapping in Leaflet

Packages required so far for data wrangling, cleaning, scraping. Thank you Hadley Wickham and Kyle Walker per usual.

library(dplyr)
library(rvest)
library(tidyr)
library(tigris)
library(leaflet)

I scraped the majority of it from the Green Papers using rvest. Painstakingly going through each state to make sure there wasn’t any serious flaws or discrepancies, I had to redo this step quite a bit. Learned a lot about our country’s geography. Did you know that Alaska only has one Congressional district?

I also removed Texas from the analysis because it uses state senatorial districts, instead of the uniform Congressional districts. Get with the program, Texans.

Spoiler alert, also working on the Republicans. May I say what an absolute pleasure the Democrats at least award their delegates proportionally in some consistent fashion…sigh.

cd114 <- congressional_districts(cb = TRUE, resolution = '20m')
delegate_map<- geo_join(cd114, test2, "GEOID", "GEOID") 
#test2 is my dataframe of election results, will add later
popup <- paste0("Congressional District ", delegate_map@data$CD114FP, "<br>", "Hillary Win: ", round(delegate_map$percent,2))
pal <- colorNumeric(palette = "Blues", domain = delegate_map$percent)
map<-leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(data = delegate_map, 
              fillColor = ~pal(percent), 
              fillOpacity = 1, 
              weight = .3, 
              smoothFactor = 0.5,
              popup = popup)

No big surprises here. Hillary does well in the South and bigger states. Now that I have the results in CD format, it will be quite easy to join to Census data to examine further trends. I’m working on a Shiny app to dig into this more deeply, along with the Republican demographics as well. Thoughts and suggestions welcome.

comments powered by Disqus