Last active
November 7, 2020 12:57
-
-
Save japhir/06b676760a86c8c8d4aa9dd48cbc5e6f to your computer and use it in GitHub Desktop.
Creates a plot of trendlines of votes remaining vs difference between candidates
This file contains 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) | |
dat <- read_csv("https://github.com/alex/nyt-2020-election-scraper/raw/master/battleground-state-changes.csv") | |
dat <- dat %>% | |
group_by(state) %>% | |
mutate(lead_first = first(leading_candidate_name), | |
biden_trump = ifelse(leading_candidate_name != lead_first | leading_candidate_name == "Trump", | |
-vote_differential, vote_differential)) %>% | |
ungroup() | |
# a faceted plot, highlighting differences between the states | |
pl <- dat %>% | |
ggplot(aes(x = votes_remaining, y = biden_trump, colour = leading_candidate_name)) + | |
geom_hline(yintercept = 0L) + | |
geom_vline(xintercept = 0L) + | |
geom_smooth(aes(group = "all"), colour = "black", method = "lm", fullrange = TRUE) + | |
geom_point() + | |
scale_x_reverse() + | |
## coord_cartesian(xlim = c(NA, 0), ylim = range(dat$biden_trump)) + | |
scale_colour_manual(values = c("Biden" = "#0015bc", "Trump" = "#ff0000")) + | |
labs(title = "US Elections 2020", | |
subtitle = paste("last updated on", lubridate::now()), | |
caption = "Data courtesy NYT, scraped by https://github.com/alex/nyt-2020-election-scraper", | |
x = "Estimate of remaining votes", | |
y = "Biden votes" ~ - ~ "Trump votes", | |
colour = "Candidate") + | |
facet_wrap( ~ state) | |
ggsave("bidenvstrumplead.png", pl, width = 10, height = 7) | |
# a single plot with all states | |
pl <- dat %>% | |
ggplot(aes(x = votes_remaining, y = biden_trump, colour = state)) + | |
geom_hline(yintercept = 0L) + | |
geom_vline(xintercept = 0L) + | |
annotate("rect", xmin = -Inf, xmax = +Inf, ymin = 0, ymax = Inf, fill = "#0015bc", alpha = .3) + | |
annotate("text", x = 5e5, y = 3e5, label = "Biden win") + | |
annotate("rect", xmin = -Inf, xmax = +Inf, ymin = -Inf, ymax = 0, fill = "#ff0000", alpha = .3) + | |
annotate("text", x = 5e5, y = -3e5, label = "Trump win") + | |
geom_smooth(method = "lm", fullrange = TRUE) + | |
geom_point() + | |
scale_x_reverse() + | |
coord_cartesian(xlim = c(NA, 0)) + | |
scale_colour_viridis_d() + | |
labs(title = "US Elections 2020", | |
subtitle = paste("last updated on", lubridate::now()), | |
caption = "Data courtesy NYT, scraped by https://github.com/alex/nyt-2020-election-scraper", | |
x = "Estimate of remaining votes", | |
y = "Biden votes" ~ - ~ "Trump votes", | |
colour = "State") | |
ggsave("bidenvstrump_allstates.png", pl, width = 10, height = 7) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment