This project uses American Community Survey data from the U.S. Census Bureau to show what the median household income across Davidson County and the counties that surround it.
############################################################
# STEP 1: Load Packages
############################################################
if (!require("tidycensus")) install.packages("tidycensus")
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("kableExtra")) install.packages("kableExtra")
if (!require("sf")) install.packages("sf")
if (!require("leaflet")) install.packages("leaflet")
if (!require("htmlwidgets")) install.packages("htmlwidgets")
if (!require("plotly")) install.packages("plotly")
library(tidycensus)
library(tidyverse)
library(kableExtra)
library(sf)
library(leaflet)
library(htmlwidgets)
library(plotly)
############################################################
# STEP 2: Verify Census API Key
############################################################
if (!nzchar(Sys.getenv("CENSUS_API_KEY"))) {
stop(
paste(
"\nNo Census API key was found.",
"\n\nTo obtain a free Census API key, visit:",
"\nhttps://api.census.gov/data/key_signup.html",
"\n\nAfter obtaining your key, run the",
"\none-time setup code shown above.",
"\n"
)
)
}
############################################################
# STEP 3: Configure Your Analysis
############################################################
# ACS year
acs_year <- 2024
# State abbreviation
state_abbrev <- "TN"
# ACS variable
# Examples:
# DP05_0001 = Total population
# DP03_0062 = Median Household Income
# DP03_0128P = Poverty Rate
# DP02_0068P = Bachelor's Degree or Higher Rate
# DP05_0018 = Median Age
# DP04_0046P = Homeownership Rate
# DP04_0134 = Median Gross Rent
# DP04_0142P = Rent Burden Rate
# DP05_0090P = Hispanic or Latino Population Percentage
# DP02_0094P = Foreign-Born Percentage
# DP03_0009P = Unemployment Rate
# DP03_0025 = Average Commute Time
my_variable <- "DP03_0062"
# Geography level
# Recommended ACS geography options:
# "county"
# "county subdivision"
# "tract"
geography_level <- "county"
# County filter
# Use NULL to include all counties in the state.
# Examples:
# selected_counties <- NULL
# selected_counties <- "Rutherford"
# selected_counties <- c(
# "Davidson",
# "Rutherford",
# "Williamson",
# "Cheatham",
# "Robertson",
# "Sumner",
# "Wilson"
# )
selected_counties <- c(
"Davidson",
"Rutherford",
"Williamson",
"Cheatham",
"Robertson",
"Sumner",
"Wilson"
)
############################################################
# STEP 4: Explore ACS Codebooks (Optional)
############################################################
ProfileTables <- load_variables(
acs_year,
"acs5/profile"
)
# DetailedTables <- load_variables(
# acs_year,
# "acs5"
# )
# SubjectTables <- load_variables(
# acs_year,
# "acs5/subject"
# )
############################################################
# STEP 5: Download ACS Data
############################################################
if (is.null(selected_counties)) {
mydata <- get_acs(
geography = geography_level,
state = state_abbrev,
year = acs_year,
survey = "acs5",
variables = my_variable,
geometry = TRUE
)
} else {
mydata <- get_acs(
geography = geography_level,
state = state_abbrev,
county = selected_counties,
year = acs_year,
survey = "acs5",
variables = my_variable,
geometry = TRUE
)
}
############################################################
# STEP 6: Keep Needed Variables and Geometry
############################################################
mydata <- mydata |>
select(
Area = NAME,
Variable = variable,
Estimate = estimate,
Margin_of_Error = moe,
geometry
)
############################################################
# STEP 7: Transform Coordinates for Leaflet
############################################################
mydata <- st_transform(
mydata,
crs = 4326
)
############################################################
# STEP 8: Download County Boundaries (Optional Overlay)
############################################################
if (is.null(selected_counties)) {
county_boundaries <- get_acs(
geography = "county",
state = state_abbrev,
year = acs_year,
survey = "acs5",
variables = my_variable,
geometry = TRUE
)
} else {
county_boundaries <- get_acs(
geography = "county",
state = state_abbrev,
county = selected_counties,
year = acs_year,
survey = "acs5",
variables = my_variable,
geometry = TRUE
)
}
county_boundaries <- st_transform(
county_boundaries,
4326
)
############################################################
# STEP 9: Sort Results from Highest to Lowest
############################################################
mydata <- mydata |>
arrange(desc(Estimate))
############################################################
# STEP 10: Display Results as a Table
############################################################
ResultsTable <- mydata |>
st_drop_geometry() |>
kbl(
col.names = c(
"Area",
"Variable",
"Estimate",
"Margin of Error"
),
format.args = list(big.mark = ",")
) |>
kable_styling(
bootstrap_options = c("striped", "hover"),
full_width = FALSE
)
############################################################
# STEP 11: Create Pop-Up Content
############################################################
mydata$popup <- paste0(
"<strong>", mydata$Area, "</strong>",
"<br><br>",
"Estimate: ",
format(mydata$Estimate, big.mark = ","),
"<br>",
"Plus/Minus: ",
format(mydata$Margin_of_Error, big.mark = ",")
)
############################################################
# STEP 12: Build Color Palette
############################################################
qs <- unique(
quantile(
mydata$Estimate,
probs = seq(0, 1, length.out = 6),
na.rm = TRUE
)
)
pal <- colorBin(
palette = "Blues",
domain = mydata$Estimate,
bins = qs,
pretty = FALSE
)
############################################################
# STEP 13: Create Choropleth Map
############################################################
AreaMap <- leaflet(mydata) |>
addProviderTiles(
providers$Esri.WorldTopoMap
) |>
addPolygons(
fillColor = ~pal(Estimate),
fillOpacity = 0.5,
color = "black",
weight = 1,
popup = ~popup
)
# Optional county boundary overlay for
# sub-county geographies
if (geography_level != "county") {
AreaMap <- AreaMap |>
addPolygons(
data = county_boundaries,
fill = FALSE,
color = "black",
weight = 2,
opacity = 1,
group = "County Boundaries"
)
}
AreaMap <- AreaMap |>
addLegend(
pal = pal,
values = ~Estimate,
title = "Estimate",
labFormat = labelFormat(
big.mark = ","
)
)
############################################################
# STEP 14: Create Plotly Dot Plot
############################################################
plotdf <- mydata |>
st_drop_geometry() |>
mutate(
point_color = pal(Estimate),
y_ordered = reorder(
Area,
Estimate
),
hover_text = paste0(
Area,
"\nEstimate: ",
format(Estimate, big.mark = ","),
"\nPlus/Minus: ",
format(Margin_of_Error, big.mark = ",")
)
)
DotPlot <- plot_ly(
data = plotdf,
x = ~Estimate,
y = ~as.character(y_ordered),
type = "scatter",
mode = "markers",
showlegend = FALSE,
marker = list(
color = ~point_color,
size = 8,
line = list(
color = "rgba(120,120,120,0.9)",
width = 0.5
)
),
error_x = list(
type = "data",
array = ~Margin_of_Error,
arrayminus = ~Margin_of_Error,
color = "rgba(0,0,0,0.65)",
thickness = 1
),
text = ~hover_text,
hovertemplate = "%{text}"
) |>
layout(
title = list(
text = paste0(
"ACS Estimates by Geography",
"\nError bars show ACS margins of error."
)
),
xaxis = list(
title = "Estimate",
tickformat = ",.0f",
automargin = TRUE
),
yaxis = list(
title = "",
automargin = TRUE,
categoryorder = "array",
categoryarray = levels(plotdf$y_ordered)
),
margin = list(
l = 200,
r = 20,
b = 60,
t = 60,
pad = 2
)
)
############################################################
# STEP 15: Export Dot Plot (Optional)
############################################################
saveWidget(
widget = as_widget(DotPlot),
file = "ACSGraph.html",
selfcontained = TRUE
)
############################################################
# STEP 16: Export Map (Optional)
############################################################
saveWidget(
widget = AreaMap,
file = "ACSMap.html",
selfcontained = TRUE
)
############################################################
# STEP 17: Show output
############################################################
DotPlot # The dot plot with error bars
AreaMap # The map
# Display the results table
ResultsTable
| Area | Variable | Estimate | Margin of Error |
|---|---|---|---|
| Williamson County, Tennessee | DP03_0062 | 135,594 | 4,044 |
| Wilson County, Tennessee | DP03_0062 | 95,839 | 3,023 |
| Sumner County, Tennessee | DP03_0062 | 90,301 | 2,629 |
| Cheatham County, Tennessee | DP03_0062 | 89,852 | 6,619 |
| Rutherford County, Tennessee | DP03_0062 | 85,470 | 1,909 |
| Robertson County, Tennessee | DP03_0062 | 83,047 | 4,193 |
| Davidson County, Tennessee | DP03_0062 | 77,853 | 1,253 |
The following R code was used.
# Step 1: Load packages
library(tidycensus)
library(tidyverse)
library(kableExtra)
library(sf)
library(leaflet)
library(htmlwidgets)
library(plotly)
# Step 2: Verify Census API key
Sys.getenv("CENSUS_API_KEY")
# Step 3: Configure analysis
acs_year <- 2024
selected_counties <- c(
"Davidson",
"Rutherford",
"Williamson",
"Cheatham",
"Robertson",
"Sumner",
"Wilson"
)
# Step 4: Load ACS variable information
acs_variables <- load_variables(
acs_year,
"acs5/profile"
)
# Step 5: Download ACS data
CountyData <- get_acs(
geography = "county",
variables = "DP03_0062",
year = acs_year,
survey = "acs5/profile",
state = "TN",
county = selected_counties,
geometry = TRUE
)
# Step 6: Select and rename columns
CountyData <- CountyData %>%
select(
NAME,
estimate,
moe,
geometry
) %>%
rename(
County = NAME,
MedianIncome = estimate,
MarginOfError = moe
)
# Step 7: Transform coordinate reference system
CountyData <- st_transform(
CountyData,
crs = 4326
)
# Step 8: Download county boundaries
CountyBoundaries <- CountyData %>%
select(County, geometry)
# Step 9: Arrange counties by median household income
CountyData <- CountyData %>%
arrange(desc(MedianIncome))
# Step 10: Create results table
ResultsTable <- CountyData %>%
st_drop_geometry() %>%
select(
County,
MedianIncome,
MarginOfError
) %>%
kbl(
caption = "Median Household Income by County",
col.names = c(
"County",
"Median Household Income",
"Margin of Error"
),
digits = 0
) %>%
kable_styling(
bootstrap_options = c(
"striped",
"hover",
"condensed"
),
full_width = FALSE
)
# Step 11: Create map popup content
CountyData$popup <- paste0(
"<strong>",
CountyData$County,
"</strong><br>",
"Median Household Income: $",
format(
CountyData$MedianIncome,
big.mark = ","
)
)
# Step 12: Create color palette
pal <- colorBin(
palette = "YlGnBu",
domain = CountyData$MedianIncome,
bins = 5
)
# Step 13: Create interactive county map
AreaMap <- leaflet(CountyData) %>%
addProviderTiles("CartoDB.Positron") %>%
addPolygons(
fillColor = ~pal(MedianIncome),
weight = 2,
opacity = 1,
color = "white",
fillOpacity = 0.7,
popup = ~popup
) %>%
addLegend(
pal = pal,
values = ~MedianIncome,
title = "Median Household Income",
position = "bottomright",
labFormat = labelFormat(
prefix = "$",
big.mark = ","
)
)
# Step 14: Create interactive dot plot
DotPlot <- plot_ly(
data = CountyData,
x = ~MedianIncome,
y = ~reorder(County, MedianIncome),
type = "scatter",
mode = "markers",
error_x = list(
type = "data",
array = ~MarginOfError,
visible = TRUE
)
) %>%
layout(
title = "Median Household Income by County",
xaxis = list(
title = "Median Household Income",
tickprefix = "$",
separatethousands = TRUE
),
yaxis = list(
title = "County"
)
)
# Step 15: Save interactive dot plot
saveWidget(
DotPlot,
"ACSGraph.html",
selfcontained = TRUE
)
# Step 16: Save interactive county map
saveWidget(
AreaMap,
"ACSMap.html",
selfcontained = TRUE
)
# Step 17: Display results
DotPlot
AreaMap
ResultsTable