Created
November 9, 2016 16:15
-
-
Save jilmun/b9b771c24798970688f279d60977a399 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
library(ggrepel) | |
library(scales) | |
results <- read_csv("results.csv") | |
# add GDP rank, winning candidate, chart labels | |
results <- results %>% | |
arrange(desc(GDP)) %>% | |
mutate(GDPRank = 1:51) %>% | |
mutate(Win = ifelse(ClintonNum>TrumpNum, "Clinton", "Trump")) %>% | |
mutate(Label = paste0(State_Abb, " [", `Electoral Votes`, "]")) | |
# create tidy data, separate camelcase column | |
results_tidy <- results %>% | |
gather(key, value, -State, -`Electoral Votes`, -GDP, -State_Abb, -GDPRank, -Win, -Label) %>% | |
separate(key, c("Candidate", "VoteType"), "(?<=.)(?=[A-Z])") %>% | |
spread(VoteType, value) | |
# scatter plot | |
ggplot(results_tidy %>% filter(Candidate=="Clinton")) + | |
geom_point(aes(x=GDP, y=Pct, size=`Electoral Votes`, col=Win, alpha=0.5)) + | |
scale_color_manual(values=c("#0052A5", "#E0162B")) + | |
geom_hline(yintercept=0.5, col="#404040", linetype=2) + | |
annotate("text", x=2.5e6, y=0.515, label="50% Line", col="#404040") + | |
labs(title="2016 Election Results vs. GDP by State") + | |
scale_y_continuous(name="Percent of Votes for Clinton", labels=percent) + | |
scale_x_log10(name="GDP (in millions $USD) from Wikipedia", | |
breaks=trans_breaks("log10", function(x) 10^x), | |
labels=trans_format("log10", math_format(10^.x))) + | |
geom_text_repel( | |
# data=subset(results_tidy %>% filter(Candidate=="Clinton"), GDPRank<=10), | |
aes(x=GDP, y=Pct, label=Label), | |
fontface="bold") + theme_bw(base_size=12) + | |
theme(legend.position="none") + | |
annotate("rect", xmin=0.9e6, xmax=3e6, ymin=0.865, ymax=0.93, fill="#FFFBCC") + | |
annotate("text", x=1e6, y=0.90, | |
label="Labels: State [Electoral Votes]\nSize: Number of Electoral Votes", | |
col="#404040", fontface="bold.italic", hjust=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment