The Middle Tennessee Commute: Project Explanation

Purpose of the project

I chose this project because commuting and traffic congestion are common topics of conversation across Middle Tennessee. I wanted to examine what Census data could tell us about how long residents spend getting to work and where their jobs are located. I initially planned to focus on Rutherford County, but I decided a comparison with Davidson, Montgomery, Williamson and Wilson counties would provide a more useful picture of the region.

I also wanted to see how the findings changed over time. I selected 2014, 2019 and 2024 to compare three points across a decade. As a journalist, I see this as a starting point for future reporting. The findings can help me ask residents more informed questions about their commutes and examine how their experiences compare with publicly available data. However, this project does not establish the causes of traffic congestion or explain individual interstate backups.

Data sources

I used two U.S. Census Bureau data sources. The first was the American Community Survey (ACS) five-year estimates, which I used to examine population and the percentage of commuters whose reported travel time to work was 30 minutes or longer. The ACS periods ending in 2014, 2019 and 2024 cover 2010–2014, 2015–2019 and 2020–2024. The commute-time measure excludes people who work from home and is not limited to people who drive.

The second source was Longitudinal Employer-Household Dynamics Origin-Destination Employment Statistics (LODES), available through the Census Bureau’s employment data program. I used primary-job origin-destination data to compare the county where a worker lives with the county where their primary job is located. This is a measure of job locations, not a record of daily trips. A job outside a worker’s home county does not necessarily mean the worker crosses the county line every day. I originally considered employment destinations within Tennessee, then expanded the study to include Tennessee’s eight bordering states: Kentucky, Virginia, North Carolina, Georgia, Alabama, Mississippi, Arkansas and Missouri. I chose this boundary because it captures additional nearby job destinations without making the project as difficult to interpret as a nationwide map. Jobs located outside these nine states are not included in the employment percentages or destination map.

Output

The project produces four visualizations covering five Middle Tennessee counties and three years.

1. Population growth: A line graph comparing population estimates in Davidson, Montgomery, Rutherford, Williamson and Wilson counties.

2. Commutes of 30 minutes or longer: A line graph comparing the percentage of commuters reporting travel times of at least 30 minutes.

3. Where residents’ primary jobs are located: A percentage-based stacked bar graph dividing jobs into three categories: inside the home county, another Tennessee county and a Tennessee bordering state. Its percentages use only jobs located within the nine-state study area.

4. Interactive job-destination map: A Leaflet map allowing readers to select a home county and year and hover over destination counties to view primary-job counts and the share of included jobs located there.

The first two graphs use ACS estimates; the last two use LODES primary-job data. Together, they show differences in reported commute times and job locations, but they should not be interpreted as proof that employment destinations caused changes in travel time.

My role in developing the script

I developed the project idea and chose the research questions, five counties and comparison years. I initially wanted to focus on Rutherford County, but I expanded the project because I thought readers would want to compare commuting patterns across the region. I also decided what information each visualization should communicate and how readers should be able to explore it.

One of my biggest design decisions involved the job-destination visualization. My original idea was a bar graph showing destination counties. As I explored more data, I realized a long list of destination counties would be crowded and difficult to follow. I decided an interactive map would be a better way to present that information. I also chose to include Tennessee’s eight bordering states rather than attempting to display the entire country. I used ChatGPT to help write and revise R code, prepare data for the visualizations, explain what different parts of the scripts were doing, and troubleshoot errors.

My role included directing the analysis, deciding which results I wanted to display, running the code in RStudio, identifying problems, testing suggested fixes and reviewing whether the output matched my intentions. For example, I wanted employment details to appear when a reader hovered over a destination county rather than displaying all the information at once.

Things I learned while developing the project

I learned that data visualization involves more than getting a script to run. It requires deciding what readers need to know, selecting a format that makes the information understandable and checking that the final display accurately represents the data. The change from a destination bar graph to an interactive map was a good example. I realized that a chart can contain accurate numbers but still be difficult for an audience to interpret. I also learned more about how commuting patterns differ among Middle Tennessee counties.

Wilson County stood out to me because a particularly large share of commuters report trips of 30 minutes or longer, and the earlier results suggested that share had grown over time. Davidson County appeared to have a comparatively smaller share of longer commutes. Montgomery County was interesting because a noticeable share of the primary jobs held by its residents in the study area were located in bordering states. Although the data cannot identify how often those workers cross state lines. I also noticed a slight decline in Rutherford County’s longer-commute share in the most recent comparison.

Another important lesson was the difference between the two datasets. The ACS tells me about reported travel time to work, while LODES tells me where primary jobs are located relative to workers’ homes. Neither dataset tracks the routes people drive or explains why an interstate becomes congested. Understanding that distinction helped me think more carefully about how to describe the findings.

As a journalist, I see the project as a foundation for additional reporting. The data can help me identify questions worth asking, find communities where commute experiences may be changing and provide context when interviewing residents. It can’t replace those interviews or prove the causes of traffic problems, but it can make future reporting more informed.

Finally, I learned that AI can be useful for coding and troubleshooting without replacing the researcher’s judgment. I had to be specific about what I wanted, test the suggestions and recognize when a proposed fix did not produce the correct result. I became more comfortable breaking problems into smaller pieces, checking the data separately from the graphics and simplifying code when necessary.

How the scripts work

The project uses two main analysis scripts. Here is a summary, written by ChatGPT but edited and checked by me, of what each step in the script accomplishes.

1. Loads the necessary R packages. The scripts use packages for Census data, data cleaning, charts, interactive graphics and mapping.

2. Defines the study area and years. The analysis focuses on Davidson, Montgomery, Rutherford, Williamson and Wilson counties and compares 2014, 2019 and 2024.

3. Retrieves and prepares ACS estimates. The first script obtains population and travel-time-to-work estimates for the five counties and organizes them by county and year.

4. Calculates longer-commute percentages. It divides the number of commuters reporting travel times of at least 30 minutes by the total number of commuters in the applicable ACS travel-time table, then converts the result to a percentage.

5. Creates the first two graphics. It plots population estimates and the longer-commute percentages for each county across the three ACS reporting periods.

6. Prepares LODES primary-job records. The employment workflow uses origin-destination records for the selected home counties and workplaces in Tennessee and its eight bordering states. It aggregates the job counts by home county, workplace county and year.

7. Classifies employment destinations. The second analysis groups primary jobs into those located in the home county, another Tennessee county or a bordering state.

8. Calculates shares for the employment chart. It divides each destination-category job count by the total primary jobs recorded within the nine-state study area for the same home county and year.

9. Creates the employment-location graph. It displays the three destination categories as stacked percentages so readers can compare the distribution across counties and years.

10. Loads county boundaries for the map. The mapping portion obtains county geographic boundaries and matches them to the aggregated destination-job counts.

11. Prepares the interactive map layers. It calculates destination-county job counts and shares, assigns color ranges and prepares the information that appears when readers hover over a county.

12. Builds the Leaflet map. It creates separate selectable layers for each home-county/year combination and adds the hover information, layer controls and legend.

13. Displays the visualizations. The R Markdown audience report presents the graphs and interactive map without displaying the analysis code, while this document explains the process.

14. Packages the HTML for publication. The audience report uses self_contained: true in its R Markdown HTML output settings so the interactive visualizations and their supporting resources are embedded in the published HTML file.

The complete scripts

############################################################
# THE MIDDLE TENNESSEE COMMUTE
# PHASE 1: UPDATED ACS DATA COLLECTION
# YEARS: 2014, 2019, 2024
############################################################

############################################################
# STEP 1: Load Packages
############################################################

if (!require("tidycensus")) install.packages("tidycensus")
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("kableExtra")) install.packages("kableExtra")
if (!require("plotly")) install.packages("plotly")

library(tidycensus)
library(tidyverse)
library(kableExtra)
library(plotly)

# CHECK YOUR CENSUS API KEY
# TRUE means your key is already available.

print(nzchar(Sys.getenv("CENSUS_API_KEY")))

# If FALSE, run the following line ONCE with your key.
# Remove the # at the beginning before running.
# Afterward, comment it out again and restart RStudio.
#
# census_api_key("PASTE_YOUR_KEY_HERE", install = TRUE)


############################################################
# STEP 2: Select Counties, Years, and ACS Variables
############################################################

# Five Middle Tennessee counties

my_counties <- c(
  "Rutherford",
  "Davidson",
  "Williamson",
  "Wilson",
  "Montgomery"
)

# Non-overlapping ACS five-year estimates

my_years <- c(2014, 2019, 2024)

# Census variables for population, age, commuting,
# and working from home

my_variables <- c(
  Population = "B01003_001",
  Median_Age = "B01002_001",
  
  # Total workers and working from home
  Total_Workers = "B08301_001",
  Work_From_Home = "B08301_021",
  
  # Total workers who did not work from home
  Total_Commuters = "B08303_001",
  
  # Commute times under 30 minutes
  Commute_Under_5 = "B08303_002",
  Commute_5_9 = "B08303_003",
  Commute_10_14 = "B08303_004",
  Commute_15_19 = "B08303_005",
  Commute_20_24 = "B08303_006",
  Commute_25_29 = "B08303_007",
  
  # Commute times 30 minutes or longer
  Commute_30_34 = "B08303_008",
  Commute_35_39 = "B08303_009",
  Commute_40_44 = "B08303_010",
  Commute_45_59 = "B08303_011",
  Commute_60_89 = "B08303_012",
  Commute_90_Plus = "B08303_013"
)


############################################################
# STEP 3: Download ACS Five-Year Estimates
############################################################

mydata <- purrr::map_dfr(
  my_years,
  function(my_year) {
    
    get_acs(
      geography = "county",
      state = "TN",
      year = my_year,
      survey = "acs5",
      variables = my_variables,
      output = "wide"
    ) |>
      mutate(Year = my_year)
    
  }
)


############################################################
# STEP 4: Keep Five Middle Tennessee Counties
############################################################

mydata <- mydata |>
  mutate(
    County = str_remove(NAME, " County, Tennessee")
  ) |>
  filter(County %in% my_counties)


############################################################
# STEP 5: Organize Dataset
############################################################

mydata <- mydata |>
  select(
    County,
    Year,
    GEOID,
    everything(),
    -NAME
  ) |>
  arrange(County, Year)


############################################################
# STEP 6: Inspect Dataset
############################################################

# View variable names and types

glimpse(mydata)

# Display all county-year records

print(mydata, n = 15)

# Confirm five counties across three years

stopifnot(nrow(mydata) == 15)

# Check for missing values

colSums(is.na(mydata))


############################################################
# STEP 7: Display Results as a Table
############################################################

ResultsTable <- mydata |>
  select(
    County,
    Year,
    Population = PopulationE,
    Median_Age = Median_AgeE,
    Total_Workers = Total_WorkersE,
    Work_From_Home = Work_From_HomeE,
    Total_Commuters = Total_CommutersE
  ) |>
  mutate(Year = as.character(Year)) |>
  kbl(
    col.names = c(
      "County",
      "Year",
      "Population",
      "Median Age",
      "Total Workers",
      "Work From Home",
      "Total Commuters"
    ),
    format.args = list(big.mark = ","),
    caption = "Middle Tennessee Population and Commuting"
  ) |>
  kable_styling(
    bootstrap_options = c("striped", "hover"),
    full_width = FALSE
  )

ResultsTable


############################################################
# STEP 8: Save Updated Dataset as CSV
############################################################

write_csv(
  mydata,
  "Middle_Tennessee_Commute_Data_2024.csv"
)


############################################################
# STEP 9: Check Variables for Codebook
############################################################

glimpse(mydata)

names(mydata)

colSums(is.na(mydata))


############################################################
# STEP 10: Create Interactive Population Growth Graph
############################################################

# Prepare population data

population_graph <- mydata %>%
  select(County, Year, Population = PopulationE) %>%
  arrange(County, Year)

# Create graph

population_plot <- ggplot(
  population_graph,
  aes(
    x = Year,
    y = Population,
    color = County,
    group = County,
    text = paste0(
      "County: ", County,
      "<br>Year: ", Year,
      "<br>Population: ", scales::comma(Population)
    )
  )
) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  scale_x_continuous(
    breaks = c(2014, 2019, 2024)
  ) +
  scale_y_continuous(labels = scales::comma) +
  labs(
    title = "Population Growth in Middle Tennessee",
    subtitle = "Five counties, 2014-2024",
    x = "Year",
    y = "Population",
    color = "County",
    caption = "Source: U.S. Census Bureau, ACS 5-Year Estimates"
  ) +
  theme_minimal(base_size = 13)

# Make graph interactive

population_interactive <- ggplotly(
  population_plot,
  tooltip = "text"
)

# Display graph

population_interactive


############################################################
# STEP 11: Create Interactive Commute Time Graph
############################################################

# Calculate commuters traveling 30 minutes or longer

commute_graph <- mydata %>%
  mutate(
    Long_Commuters = Commute_30_34E +
      Commute_35_39E +
      Commute_40_44E +
      Commute_45_59E +
      Commute_60_89E +
      Commute_90_PlusE,
    
    Long_Commute_Percent = round(
      Long_Commuters / Total_CommutersE * 100, 1
    )
  ) %>%
  select(
    County,
    Year,
    Total_CommutersE,
    Long_Commuters,
    Long_Commute_Percent
  )

# Create graph

commute_plot <- ggplot(
  commute_graph,
  aes(
    x = Year,
    y = Long_Commute_Percent,
    color = County,
    group = County,
    text = paste0(
      "County: ", County,
      "<br>Year: ", Year,
      "<br>30+ Minute Commuters: ",
      scales::comma(Long_Commuters),
      "<br>Percentage: ", Long_Commute_Percent, "%"
    )
  )
) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  scale_x_continuous(
    breaks = c(2014, 2019, 2024)
  ) +
  scale_y_continuous(
    labels = function(x) paste0(x, "%")
  ) +
  labs(
    title = "Commuters Traveling 30 Minutes or Longer",
    subtitle = "Five Middle Tennessee counties, 2014-2024",
    x = "Year",
    y = "Percentage of Commuters",
    color = "County",
    caption = "Source: U.S. Census Bureau, ACS 5-Year Estimates"
  ) +
  theme_minimal(base_size = 13)

# Make graph interactive

commute_interactive <- ggplotly(
  commute_plot,
  tooltip = "text"
)

# Display graph

commute_interactive

############################################################
# END OF UPDATED ACS SCRIPT
############################################################
############################################################
# THE MIDDLE TENNESSEE COMMUTE
# SCRIPT 2: CENSUS LODES EMPLOYMENT DATA
#
# GRAPH 3: WHERE PRIMARY JOBS ARE LOCATED
# GRAPH 4: INTERACTIVE JOB DESTINATION MAP
#
# Years: 2014, 2019, 2024
# Tennessee + Eight Bordering States
#
# RPubs-compatible: No Shiny
############################################################


############################################################
# STEP 1: LOAD PACKAGES
############################################################

packages <- c(
  "tidyverse",
  "plotly",
  "sf",
  "tigris",
  "leaflet",
  "htmlwidgets",
  "htmltools",
  "scales"
)

for (pkg in packages) {
  if (!requireNamespace(pkg, quietly = TRUE)) {
    install.packages(pkg)
  }
}

library(tidyverse)
library(plotly)
library(sf)
library(tigris)
library(leaflet)
library(htmlwidgets)


############################################################
# STEP 2: DEFINE COUNTIES AND YEARS
############################################################

home_counties <- c(
  "Davidson",
  "Montgomery",
  "Rutherford",
  "Williamson",
  "Wilson"
)

my_years <- c(2014, 2019, 2024)


############################################################
# STEP 3: LOAD EXPANDED EMPLOYMENT DATA
############################################################

csv_file <- "Middle_Tennessee_Border_All_Destinations_2024.csv"

if (!file.exists(csv_file)) {
  message("Select your expanded employment CSV.")
  csv_file <- file.choose()
}

jobs <- readr::read_csv(
  csv_file,
  show_col_types = FALSE
)

required_columns <- c(
  "Year",
  "Home_County",
  "Work_County",
  "Primary_Jobs"
)

stopifnot(
  all(required_columns %in% names(jobs))
)

jobs <- jobs %>%
  mutate(
    Year = as.integer(Year),
    Home_County = as.character(Home_County),
    Work_County = as.character(Work_County),
    Primary_Jobs = as.numeric(Primary_Jobs)
  ) %>%
  filter(
    Home_County %in% home_counties,
    Year %in% my_years
  ) %>%
  group_by(
    Year,
    Home_County,
    Work_County
  ) %>%
  summarise(
    Primary_Jobs = sum(Primary_Jobs),
    .groups = "drop"
  )

stopifnot(
  !any(is.na(jobs$Primary_Jobs)),
  all(jobs$Primary_Jobs >= 0)
)


############################################################
# STEP 4: CLASSIFY WORKPLACE LOCATIONS
############################################################

state_names <- c(
  TN = "Tennessee",
  KY = "Kentucky",
  VA = "Virginia",
  NC = "North Carolina",
  GA = "Georgia",
  AL = "Alabama",
  MS = "Mississippi",
  AR = "Arkansas",
  MO = "Missouri"
)

jobs <- jobs %>%
  mutate(
    Work_State = sub("^.*, ", "", Work_County),
    
    Work_Location = case_when(
      Work_County ==
        paste0(Home_County, " County, Tennessee") ~
        "Inside home county",
      
      Work_State == "Tennessee" ~
        "Another Tennessee county",
      
      TRUE ~
        "Tennessee bordering state"
    )
  )

stopifnot(
  all(jobs$Work_State %in% unname(state_names))
)


############################################################
# STEP 5: SUMMARIZE EMPLOYMENT LOCATIONS
############################################################

commute_summary <- jobs %>%
  group_by(
    Year,
    Home_County,
    Work_Location
  ) %>%
  summarise(
    Primary_Jobs = sum(Primary_Jobs),
    .groups = "drop"
  ) %>%
  group_by(
    Year,
    Home_County
  ) %>%
  mutate(
    Total_Jobs = sum(Primary_Jobs),
    Percentage = 100 * Primary_Jobs / Total_Jobs
  ) %>%
  ungroup() %>%
  tidyr::complete(
    tidyr::nesting(Year, Home_County),
    Work_Location = c(
      "Inside home county",
      "Another Tennessee county",
      "Tennessee bordering state"
    ),
    fill = list(
      Primary_Jobs = 0,
      Percentage = 0
    )
  )

stopifnot(nrow(commute_summary) == 45)

percentage_check <- commute_summary %>%
  group_by(Year, Home_County) %>%
  summarise(
    Total_Percentage = sum(Percentage),
    .groups = "drop"
  )

stopifnot(
  all(abs(percentage_check$Total_Percentage - 100) < 0.001)
)

print(commute_summary, n = 45)


############################################################
# STEP 6: CHECK WILSON COUNTY 2019
############################################################

wilson_check <- commute_summary %>%
  filter(
    Home_County == "Wilson",
    Year == 2019
  ) %>%
  arrange(Work_Location)

print(wilson_check, n = 3)

stopifnot(
  wilson_check$Primary_Jobs[
    wilson_check$Work_Location == "Inside home county"
  ] > 0
)


############################################################
# STEP 7: SAVE EMPLOYMENT SUMMARY
############################################################

readr::write_csv(
  commute_summary,
  "Middle_Tennessee_Border_Location_Summary_2024.csv"
)


############################################################
# STEP 8: PREPARE GRAPH 3
############################################################

employment_graph <- commute_summary %>%
  mutate(
    Year = factor(
      Year,
      levels = my_years
    ),
    
    Work_Location = factor(
      Work_Location,
      levels = c(
        "Inside home county",
        "Another Tennessee county",
        "Tennessee bordering state"
      )
    )
  )


############################################################
# STEP 9: CREATE GRAPH 3
############################################################

employment_plot <- ggplot(
  employment_graph,
  aes(
    x = Year,
    y = Percentage,
    fill = Work_Location,
    
    text = paste0(
      "Home County: ", Home_County,
      "<br>Year: ", Year,
      "<br>Work Location: ", Work_Location,
      "<br>Primary Jobs: ",
      scales::comma(Primary_Jobs),
      "<br>Percentage: ",
      round(Percentage, 1), "%"
    )
  )
) +
  
  geom_col(width = 0.7) +
  
  facet_wrap(
    ~ Home_County,
    ncol = 2
  ) +
  
  scale_y_continuous(
    breaks = seq(0, 100, 25),
    labels = function(x) paste0(x, "%"),
    expand = expansion(mult = c(0, 0.02))
  ) +
  
  coord_cartesian(
    ylim = c(0, 100)
  ) +
  
  scale_fill_manual(
    values = c(
      "Inside home county" = "#2878B5",
      "Another Tennessee county" = "#F28E6B",
      "Tennessee bordering state" = "#76B7B2"
    )
  ) +
  
  labs(
    title = "Where Middle Tennessee Residents Work",
    
    subtitle = paste(
      "Share of primary jobs in Tennessee and",
      "its eight bordering states, 2014–2024"
    ),
    
    x = "Year",
    y = "Percentage of Included Primary Jobs",
    fill = "Work Location",
    
    caption = paste(
      "Source: U.S. Census Bureau, LODES8, JT01.",
      "Jobs outside the nine-state region excluded."
    )
  ) +
  
  theme_minimal(base_size = 12) +
  
  theme(
    plot.title = element_text(size = 16),
    legend.position = "bottom"
  )


############################################################
# STEP 10: MAKE GRAPH 3 INTERACTIVE
############################################################

employment_interactive <- plotly::ggplotly(
  employment_plot,
  tooltip = "text"
)

print(employment_interactive)


############################################################
# STEP 11: SAVE COUNTY DESTINATION DATA
############################################################

destination_summary <- jobs %>%
  select(
    Year,
    Home_County,
    Work_County,
    Work_State,
    Work_Location,
    Primary_Jobs
  ) %>%
  arrange(
    Year,
    Home_County,
    desc(Primary_Jobs)
  )

readr::write_csv(
  destination_summary,
  "Middle_Tennessee_Border_Destinations_Final.csv"
)


############################################################
# STEP 12: LOAD CACHED COUNTY BOUNDARIES
############################################################

map_cache <- "Middle_Tennessee_County_Boundaries.rds"

if (file.exists(map_cache)) {
  
  message("Using cached county boundaries.")
  
  county_map <- readRDS(map_cache)
  
} else {
  
  message("Downloading county boundaries...")
  
  options(tigris_use_cache = TRUE)
  
  county_map <- tigris::counties(
    state = c(
      "TN", "KY", "VA", "NC", "GA",
      "AL", "MS", "AR", "MO"
    ),
    year = 2024,
    cb = TRUE,
    class = "sf"
  )
  
  saveRDS(county_map, map_cache)
}


############################################################
# STEP 13: PREPARE AND SIMPLIFY COUNTY BOUNDARIES
############################################################

county_map <- county_map %>%
  sf::st_transform(4326) %>%
  mutate(
    Work_County = paste0(
      NAMELSAD,
      ", ",
      state_names[STUSPS]
    )
  )

# Simplify boundaries to reduce HTML file size.
# County names, job counts and percentages stay unchanged.

county_map <- county_map %>%
  sf::st_transform(5070) %>%
  sf::st_simplify(
    dTolerance = 3000,
    preserveTopology = TRUE
  ) %>%
  sf::st_transform(4326)

message("SUCCESS: County boundaries simplified.")

############################################################
# STEP 14: VERIFY DESTINATIONS
############################################################

map_names <- county_map %>%
  sf::st_drop_geometry() %>%
  select(Work_County)

unmatched <- jobs %>%
  anti_join(
    map_names,
    by = "Work_County"
  )

if (nrow(unmatched) > 0) {
  print(unmatched, n = 50)
  stop("Some destinations do not match the map.")
}

message("SUCCESS: All destinations matched.")


############################################################
# STEP 15: PREPARE ALL 15 MAP COMBINATIONS
############################################################

map_layers <- list()

for (county in home_counties) {
  
  for (yr in my_years) {
    
    selected_jobs <- jobs %>%
      filter(
        Home_County == county,
        Year == yr
      ) %>%
      select(
        Work_County,
        Primary_Jobs
      )
    
    total_jobs <- sum(selected_jobs$Primary_Jobs)
    
    if (total_jobs <= 0) {
      stop("No jobs found for ", county, " ", yr)
    }
    
    current_map <- county_map %>%
      left_join(
        selected_jobs,
        by = "Work_County"
      ) %>%
      mutate(
        Percentage = 100 * Primary_Jobs / total_jobs,
        
        Hover_Text = ifelse(
          is.na(Primary_Jobs),
          
          paste0(
            "<b>", Work_County, "</b>",
            "<br>No recorded jobs in selected data"
          ),
          
          paste0(
            "<b>", Work_County, "</b>",
            "<br>Home county: ", county,
            "<br>Year: ", yr,
            "<br>Primary jobs: ",
            scales::comma(Primary_Jobs),
            "<br>Share of included jobs: ",
            round(Percentage, 2), "%"
          )
        ),
        
        Job_Band = case_when(
          is.na(Primary_Jobs) ~
            "No recorded jobs",
          Primary_Jobs >= 20000 ~
            "20,000+",
          Primary_Jobs >= 5000 ~
            "5,000–19,999",
          Primary_Jobs >= 1000 ~
            "1,000–4,999",
          Primary_Jobs >= 100 ~
            "100–999",
          Primary_Jobs >= 10 ~
            "10–99",
          TRUE ~
            "1–9"
        )
      )
    
    stopifnot(
      sum(current_map$Primary_Jobs, na.rm = TRUE) ==
        total_jobs
    )
    
    map_layers[[paste(county, yr)]] <- current_map
    
  }
}


############################################################
# STEP 16: DEFINE JOB COUNT COLORS
############################################################

job_colors <- c(
  "20,000+" = "#08306B",
  "5,000–19,999" = "#08519C",
  "1,000–4,999" = "#2171B5",
  "100–999" = "#6BAED6",
  "10–99" = "#BDD7E7",
  "1–9" = "#EFF3FF",
  "No recorded jobs" = "#E5E7EB"
)


############################################################
# STEP 17: CREATE BASE MAP
############################################################

job_map <- leaflet::leaflet(
  options = leaflet::leafletOptions(
    minZoom = 4,
    preferCanvas = TRUE
  )
) %>%
  
  leaflet::addTiles() %>%
  
  leaflet::fitBounds(
    lng1 = -94.7,
    lat1 = 29.8,
    lng2 = -75.0,
    lat2 = 39.6
  )


############################################################
# STEP 18: ADD COUNTY POLYGONS
############################################################

for (layer_name in names(map_layers)) {
  
  current_map <- map_layers[[layer_name]]
  
  job_map <- job_map %>%
    leaflet::addPolygons(
      data = current_map,
      group = layer_name,
      
      fillColor = ~unname(job_colors[Job_Band]),
      fillOpacity = 0.85,
      
      color = "#FFFFFF",
      weight = 0.5,
      opacity = 0.9,
      
      highlightOptions = leaflet::highlightOptions(
        weight = 2,
        color = "#222222",
        bringToFront = TRUE
      ),
      
      label = ~lapply(
        Hover_Text,
        htmltools::HTML
      )
    )
}


############################################################
# STEP 19: DISPLAY ONE MAP LAYER INITIALLY
############################################################

initial_layer <- "Montgomery 2024"

job_map <- job_map %>%
  leaflet::hideGroup(
    setdiff(
      names(map_layers),
      initial_layer
    )
  )


############################################################
# STEP 20: ADD SINGLE-CHOICE LAYER SELECTOR
############################################################

job_map <- job_map %>%
  leaflet::addLayersControl(
    baseGroups = names(map_layers),
    
    options = leaflet::layersControlOptions(
      collapsed = TRUE
    )
  )


############################################################
# STEP 21: ADD JOB COUNT LEGEND
############################################################

job_map <- job_map %>%
  leaflet::addLegend(
    position = "bottomright",
    colors = unname(job_colors),
    labels = names(job_colors),
    title = "Primary Jobs",
    opacity = 0.85
  )


############################################################
# STEP 22: DISPLAY GRAPH 4
############################################################

print(job_map)


############################################################
# STEP 23: FINAL VERIFICATION
############################################################

print(
  commute_summary %>%
    arrange(Home_County, Year, Work_Location),
  n = 45
)

message(
  "SUCCESS: Graph 3 and Graph 4 created."
)


############################################################
# END OF SCRIPT 2
############################################################