Skip to content

Instantly share code, notes, and snippets.

@USMortality
Last active November 20, 2024 23:24
Show Gist options
  • Save USMortality/609041077b300abcfd0ad62d16da51f3 to your computer and use it in GitHub Desktop.
Save USMortality/609041077b300abcfd0ad62d16da51f3 to your computer and use it in GitHub Desktop.
Democratic Popular Votes by Presidential Election (with Forecasts) [USA]
library(ggplot2)
library(dplyr)
library(tsibble)
library(fable)
library(feasts)
sf <- 2
width <- 600 * sf
height <- 335 * sf
options(vsc.dev.args = list(width = width, height = height, res = 72 * sf))
# Original data (1976-2020)
dem_votes <- data.frame(
Year = c(
1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020
),
Votes = c(
40831881, 35480115, 37577352, 41809074,
44909806, 47401185, 50999897, 59028444,
69498516, 65915795, 65853514, 81283501
)
)
# Add 2024 estimate
total_ballots <- 158549000
harris_original_votes <- 66936996
trump_original_votes <- 71822869
harris_votes_2024 <-
total_ballots *
(harris_original_votes / (harris_original_votes + trump_original_votes))
# Add estimated 2024 votes
dem_votes <- dem_votes %>%
add_row(Year = 2024, Votes = harris_votes_2024)
# Convert to tsibble for forecasting
dem_tsibble <- dem_votes %>% as_tsibble(index = Year)
# Fit the model with a trend component
fit <- dem_tsibble |>
filter(Year < 2020) |>
model(TSLM(Votes ~ trend()))
# Forecast for 2020 and 2024
forecast_results <- fit |>
forecast(new_data = dem_tsibble |> filter(Year >= 2020))
ts <- dem_votes |> as_tsibble(index = Year)
fc <- fit |> forecast(h = 2)
chart <- autoplot(fc, ts) + labs(
title = "Democratic Popular Votes by Presidential Election (with Forecasts)",
subtitle = "Trend 1976 - 2016, Forecast 2020 & 2024",
x = "Year",
y = "Popular Votes"
) +
theme_bw()
ggsave(
filename = "chart1.png", plot = chart, width = width, height = height,
units = "px", dpi = 72 * sf, device = grDevices::png, type = "cairo"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment