# compare data from zillow (home prices)
# with data from the 2020 election (county-level results)

# load the zillow data
# source("save_zillow_county_data.R")
library(tidyverse)
remote_dir <- "https://euclid.nmu.edu/~joshthom/dat309/week9/zdata/"
zillow_county_data <- read_csv(
  str_c(remote_dir, "zillow_county_data.csv")
)

# load election data
election_data <- read_csv(
  str_c(remote_dir, "election_data_with_county_info_2024.csv")
)

# join the two datasets on fips code
# home_prices_voting_data: hpvd
hpvd <- inner_join(
  zillow_county_data,
  election_data,
  by = "fips"
)

# make 8 categories of population density and assign
# every county to a category
# use cut variable
hpvd <- hpvd |>
  mutate(
    pop_dens_cat = cut(
      pop_dens,
      breaks = c(0, 1000, 2000, 5000, 8000, 12000, 25000, 37000, 60000),
      labels = 1:8
    )
  ) |>
  glimpse()


# visualize the distribution of redblue across the population density categories
# create a barplot x = newly created categories,
# y = redblue
hpvd |>
  ggplot(aes(x = pop_dens_cat, fill = redblue)) +
  geom_bar(position = 'fill') +
  scale_fill_manual(
    values = c("red" = "#cb181d", "blue" = "#2171b5"),
    labels = c("red" = "Republican", "blue" = "Democrat")
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# make 10 categories of home prices and assign
# every county to a category
max_min_price <- hpvd |>
  summarize(
    min_price = min(mean_home_price),
    max_price = max(mean_home_price)
  ) |>
  unlist()

price_cats <- quantile(max_min_price, probs = seq(0, 1, by = .1))

hpvd <- hpvd |>
  mutate(
    home_price_cat = cut(mean_home_price, breaks = price_cats, labels = 1:10)
  ) |>
  glimpse()

hpvd |>
  ggplot(aes(x = home_price_cat, fill = redblue)) +
  geom_bar(position = 'fill') +
  scale_fill_manual(
    values = c("red" = "#cb181d", "blue" = "#2171b5"),
    labels = c("red" = "Republican", "blue" = "Democrat")
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# visualize distribution of redblue counties by population density category
#
# this might be helpful:

# geom_bar(position = "fill") +
#  scale_fill_manual(
#    values = c("red" = "#cb181d", "blue" = "#2171b5"),
#    labels = c("red" = "Republican", "blue" = "Democrat")
#  ) +
# theme_minimal() +
#  theme(axis.text.x = element_text(angle = 45, hjust = 1))
