##Title: DWVGIS 3. Census.R
#Author: Jack Reilly
#Purpose: Illustrate using the Census API to visualize geographic data
#Requires: no external data

library(tidyverse)
library(ggthemes)
library(tidycensus)
library(ggplot2)
library(dplyr)
library(sf)

# (Run once per computer; then restart R)
#census_api_key("YOUR KEY HERE", install = TRUE)

# Load 2020 population by county, with geometry
counties <- get_decennial(
  geography = "county",
  variables = "P1_001N",   # total population
  year = 2020,
  geometry = TRUE
)

#Look at the data
counties

#Make an initial plot
ggplot(counties) +
  geom_sf(aes(fill = value), color = NA) +
  labs(title = "Population by County, 2020",
       fill = "People") +
  theme_minimal()


#Constrain graph by lat/long
ggplot(counties) +
  geom_sf(aes(fill = value), color = NA) +
  coord_sf(
    xlim = c(-125, -66),   # longitude range
    ylim = c(24, 50),      # latitude range
    expand = FALSE
  ) +
  labs(title = "Population by County, 2020",
       fill = "People") +
  theme_minimal()

# Filter out Alaska, Hawaii, Puerto Rico, etc.
counties <- counties |>
  mutate(STATEFP = substr(GEOID, 1, 2)) |>
  filter(!STATEFP %in% c("02", "15", "72"))  # AK, HI, PR

lower48 <- counties |>
  filter(!STATEFP %in% c("02", "15", "72"))  # 02 = AK, 15 = HI, 72 = PR

# Project to something appropriate for U.S. maps (Albers equal area)
lower48 <- st_transform(lower48, 5070)

# Plot
ggplot(lower48) +
  geom_sf(aes(fill = value), color = NA) +
  coord_sf(datum = NA) +
  labs(title = "Population by County, 2020",
       fill = "People") +
  theme_minimal()

#Let's use viridis color scheme!
ggplot(lower48) +
  geom_sf(aes(fill = value), color = NA) +
  scale_fill_viridis_c(labels = scales::comma) +
  coord_sf(datum = NA) +
  labs(title = "Population by County, 2020",
       fill = "People") +
  theme_minimal()

#Still not a good scale
#Fix that scale
library(scales)  # for label_number(), cut_short_scale()

#Build plot like we did before
#Note the scale transform, the breaks, and the legend simplification
p  <- ggplot(lower48, aes(fill = value)); p #This is already an sf object, so we don't have to declare lat/long!
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
  scale_fill_viridis_c(
    trans = "log10",
    breaks = c(1e2, 1e3, 1e4, 1e5, 1e6, 1e7),
    labels = label_number(scale_cut = cut_short_scale())
  ) +
  labs(title = "Population by County, 2020", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))


#I'd like to squish the bottom of the scale a little bit to show more contrast.  Not many counties with 100 people in them.
vmax <- max(lower48$value, na.rm = TRUE)

p  <- ggplot(lower48, aes(fill = value)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
  scale_fill_viridis_c(
    trans  = "log10",
    limits = c(1e3, vmax),          # start color mapping at 1,000
    oob    = squish,                # values <1,000 get the lowest color
    breaks = c(1e3, 1e4, 1e5, 1e6, 1e7),
    labels = label_number(scale_cut = cut_short_scale())
  ) +
  labs(title = "Population by County, 2020", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))

#Let's graph homeownership!

#Get the data
homeown <- get_acs(
  geography = "county",
  variables = c(total = "B25003_001", owners = "B25003_002"),
  year = 2023,
  geometry = TRUE
) |>
  mutate(STATEFP = substr(GEOID, 1, 2)) |>
  filter(!STATEFP %in% c("02","15","60","66","69","72","78")) |>  # lower 48
  st_transform(5070) |>
  select(GEOID, NAME, variable, estimate, geometry) |>
  tidyr::pivot_wider(names_from = variable, values_from = estimate) |>
  mutate(homeown_rate = 100 * owners / total)

#Graph it
#Note different style choices on color scale: homeownership is actually kind of high, so I want more yellows
p  <- ggplot(homeown, aes(fill = homeown_rate)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
  scale_fill_viridis_c(
    limits = c(40, 90),     # focus color stretch on 40–90%
    oob    = squish,
    breaks = seq(40, 90, by = 10),
    labels = label_number(suffix = "%")
  ) +
  labs(title = "Homeownership Rate by County, 2023", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))



#Let's graph income!
#Get the data
income <- get_acs(
  geography = "county",
  variables = "B19013_001",   # Median household income (past 12 months)
  year = 2023,
  geometry = TRUE
) |>
  rename(median_income = estimate) |>
  mutate(STATEFP = substr(GEOID, 1, 2)) |>
  filter(!STATEFP %in% c("02","15","60","66","69","72","78")) |>  # lower 48 only
  st_transform(5070)

#Mean and median income are both around 65k
mean(income$median_income, na.rm=T)
median(income$median_income, na.rm=T)
#Visually, I want a scale that somewhat reflects that 
#I have some high outliers, though, so I still want to do somethign with the scale
#Either cap it or transform it
library(lattice)
histogram(income$median_income, na.rm=T)

# Graph it
# This version picks capping; transform command left in
p  <- ggplot(income, aes(fill = median_income)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
  scale_fill_viridis_c(
#    trans  = "log10",
    limits = c(30000, 100000),     # stretch around typical range
    oob    = squish,
    breaks = c(30000, 50000, 70000, 90000, 110000),
    labels = label_dollar(scale_cut = cut_short_scale())
  ) +
  labs(title = "Median Household Income by County, 2023", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))

#Education!
#Get the data
edu <- get_acs(
  geography = "county",
  variables = c(
    total = "B15003_001",  # total population age 25+
    high  = "B15003_017",  # high school
    bach  = "B15003_022",  # bachelor's
    mast  = "B15003_023",  # master's
    prof  = "B15003_024",  # professional
    doct  = "B15003_025"   # doctorate
  ),
  year = 2023,
  geometry = TRUE
) |>
  select(GEOID, variable, estimate, geometry) |>
  pivot_wider(names_from = variable, values_from = estimate) |>
  mutate(
    STATEFP = substr(GEOID, 1, 2),
    ba_plus = 100 * (bach + mast + prof + doct) / total,
#    hs_plus = 100 * (high + bach + mast + prof + doct) / total
  ) |>
  filter(!STATEFP %in% c("02","15","60","66","69","72","78")) |>  # lower 48
  st_transform(5070)

# Graph it
# Here, I want my visual midpoint around 50% BA, as that creates the contrast I'm trying to illustrate
# Even though the range is a little different
mean(edu$ba_plus)
range(edu$ba_plus)

p  <- ggplot(edu, aes(fill = ba_plus)); p
p1 <- p + geom_sf(color = "gray90", linewidth = 0.05) + coord_sf(datum = NA); p1
p2 <- p1 +
  scale_fill_viridis_c(
    limits = c(10, 60),      # % adults with BA+ typically in this range
    oob    = squish,
    breaks = seq(10, 60, by = 10),
    labels = label_number(suffix = "%")
  ) +
  labs(title = "Adults 25+ with Bachelor's Degree or Higher, 2023", fill = NULL); p2
p2 + theme_map() + guides(fill = guide_colorbar(barheight = unit(60, "pt")))