# The 2026 midterm, Stat 333.  Deck: https://pages.stat.wisc.edu/~karlrohe/lr333/midterm.html
# Governor races by county, 2022 vs 2026.  2026 counts are unofficial (Nov 4, 2026).
# Maps need install.packages("maps") once.

library(tidyverse)
theme_set(theme_minimal(base_size = 14))
party_colors = c(open = "#999999", D = "#0072B2", R = "#E69F00")

gov = read_csv("https://pages.stat.wisc.edu/~karlrohe/lr333/governor_2026.csv",
               col_types = cols(fips = col_character()))


gov |> select(state_abbr, county, dem_2022, rep_2022, dem_2026, rep_2026, pct_in_2026)

gov = gov |> mutate(
  share_2022 = dem_2022 / (dem_2022 + rep_2022),
  share_2026 = dem_2026 / (dem_2026 + rep_2026),
  swing = share_2026 - share_2022,
  turnout = 2 * (dem_2026 + rep_2026) / (dem_2022 + rep_2022 + dem_2026 + rep_2026))

gov |> mutate(state = fct_reorder(state, swing, median)) |>
  ggplot(aes(100 * swing, state, fill = incumbent_2026)) +
  geom_boxplot(outlier.size = 0.6) + geom_vline(xintercept = 0) +
  scale_fill_manual(values = party_colors) +
  labs(x = "County swing toward the Democrat (percentage points)", y = NULL, fill = "2026 incumbent")

gov |> group_by(state_abbr) |>
  summarise(state_swing = sum(dem_2026) / sum(dem_2026 + rep_2026) - sum(dem_2022) / sum(dem_2022 + rep_2022),
            mean_county = mean(swing),
            weighted_county = weighted.mean(swing, dem_2026 + rep_2026)) |>
  mutate(across(-state_abbr, \(x) round(100 * x, 1))) |>
  arrange(desc(state_swing - mean_county)) |> head(8)

gov = gov |> mutate(incumbent_2026 = factor(incumbent_2026, levels = c("open", "D", "R")))
fit_inc = lm(swing ~ incumbent_2026, data = gov)
rows = match(c("open", "D", "R"), gov$incumbent_2026)
cbind(gov[rows, c("state_abbr", "county", "incumbent_2026")], model.matrix(fit_inc)[rows, ])

summary(fit_inc)

fit_state = lm(swing ~ state, data = gov)
summary(fit_state)

c(state = summary(fit_state)$r.squared, incumbent = summary(fit_inc)$r.squared)

fit_slopes = lm(share_2026 ~ share_2022 * incumbent_2026, data = gov)
summary(fit_slopes)

ggplot(gov, aes(share_2022, share_2026, color = incumbent_2026)) +
  geom_point(size = 0.8, alpha = 0.4) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE) +
  geom_abline(linetype = "dashed") +
  scale_color_manual(values = party_colors) +
  labs(x = "Democrat's two-party share, 2022", y = "Democrat's two-party share, 2026", color = "2026 incumbent")

gov = as.data.frame(gov)
rownames(gov) = paste(gov$county, gov$state_abbr)
fit = lm(swing ~ state + share_2022, data = gov)

county_map = map_data("county") |>
  mutate(polyname = paste(region, subregion, sep = ",")) |>
  left_join(maps::county.fips |> mutate(fips = sprintf("%05d", fips), polyname = str_remove(polyname, ":.*")) |> distinct(),
            by = "polyname")
gov$resid = resid(fit)
county_map |> left_join(select(gov, fips, resid), by = "fips") |>
  ggplot(aes(long, lat, group = group, fill = pmax(pmin(resid, 0.08), -0.08))) +
  geom_polygon() +
  geom_polygon(data = map_data("state"), aes(long, lat, group = group), fill = NA, color = "grey40", linewidth = 0.2) +
  scale_fill_gradient2(low = "#e66101", mid = "grey95", high = "#2166ac", na.value = "white", name = "residual") +
  coord_quickmap() + theme_void(base_size = 13)

r = resid(fit)[gov$pct_in_2026 >= 90]
sort(r, decreasing = TRUE)[1:8]
sort(r)[1:8]

county_map |> left_join(select(filter(gov, pct_in_2026 >= 95), fips, turnout), by = "fips") |>
  ggplot(aes(long, lat, group = group, fill = pmax(pmin(turnout, 1.2), 0.8))) +
  geom_polygon() +
  geom_polygon(data = map_data("state"), aes(long, lat, group = group), fill = NA, color = "grey40", linewidth = 0.2) +
  scale_fill_gradient2(low = "#e66101", mid = "grey95", high = "#5e3c99", midpoint = 1, na.value = "white", name = "turnout") +
  coord_quickmap() + theme_void(base_size = 13)

counted = filter(gov, pct_in_2026 >= 95)
fit_t = lm(swing ~ state + share_2022 + turnout, data = counted)
summary(fit_t)
