############################################################
# STEP 1: Load Packages
############################################################
if (!require("tidycensus")) install.packages("tidycensus")
## Loading required package: tidycensus
if (!require("tidyverse")) install.packages("tidyverse")
## Loading required package: tidyverse
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.2.1 ✔ readr 2.2.0
## ✔ forcats 1.0.1 ✔ stringr 1.6.0
## ✔ ggplot2 4.0.3 ✔ tibble 3.3.1
## ✔ lubridate 1.9.5 ✔ tidyr 1.3.2
## ✔ purrr 1.2.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
if (!require("kableExtra")) install.packages("kableExtra")
## Loading required package: kableExtra
##
## Attaching package: 'kableExtra'
##
## The following object is masked from 'package:dplyr':
##
## group_rows
if (!require("sf")) install.packages("sf")
## Loading required package: sf
## Linking to GEOS 3.14.1, GDAL 3.12.1, PROJ 9.7.1; sf_use_s2() is TRUE
if (!require("leaflet")) install.packages("leaflet")
## Loading required package: leaflet
if (!require("htmlwidgets")) install.packages("htmlwidgets")
## Loading required package: htmlwidgets
if (!require("plotly")) install.packages("plotly")
## Loading required package: plotly
##
## Attaching package: 'plotly'
##
## The following object is masked from 'package:ggplot2':
##
## last_plot
##
## The following object is masked from 'package:stats':
##
## filter
##
## The following object is masked from 'package:graphics':
##
## layout
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 subdivision" #<< NEW LEVEL
# 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
)
}
## Getting data from the 2020-2024 5-year ACS
## Downloading feature geometry from the Census website. To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
## Using the ACS Data Profile
############################################################
# 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
)
}
## Getting data from the 2020-2024 5-year ACS
## Downloading feature geometry from the Census website. To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
## Using the ACS Data Profile
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
ResultsTable
| Area | Variable | Estimate | Margin of Error |
|---|---|---|---|
| District 6, Williamson County, Tennessee | DP03_0062 | 193,273 | 16,236 |
| District 7, Williamson County, Tennessee | DP03_0062 | 187,123 | 15,963 |
| District 34, Davidson County, Tennessee | DP03_0062 | 167,813 | 14,258 |
| District 5, Williamson County, Tennessee | DP03_0062 | 163,988 | 23,357 |
| District 9, Williamson County, Tennessee | DP03_0062 | 162,262 | 19,826 |
| District 2, Williamson County, Tennessee | DP03_0062 | 149,080 | 23,328 |
| District 5, Wilson County, Tennessee | DP03_0062 | 141,184 | 23,645 |
| District 4, Williamson County, Tennessee | DP03_0062 | 130,607 | 12,937 |
| District 25, Davidson County, Tennessee | DP03_0062 | 129,511 | 11,858 |
| District 10, Williamson County, Tennessee | DP03_0062 | 124,464 | 14,997 |
| District 35, Davidson County, Tennessee | DP03_0062 | 123,164 | 5,282 |
| District 8, Williamson County, Tennessee | DP03_0062 | 122,778 | 19,022 |
| District 10, Wilson County, Tennessee | DP03_0062 | 122,750 | 35,074 |
| District 16, Wilson County, Tennessee | DP03_0062 | 122,734 | 44,662 |
| District 23, Davidson County, Tennessee | DP03_0062 | 122,201 | 13,587 |
| District 12, Williamson County, Tennessee | DP03_0062 | 122,154 | 8,374 |
| District 4, Wilson County, Tennessee | DP03_0062 | 121,953 | 6,310 |
| District 3, Williamson County, Tennessee | DP03_0062 | 121,242 | 11,125 |
| District 2, Wilson County, Tennessee | DP03_0062 | 120,280 | 15,914 |
| District 14, Rutherford County, Tennessee | DP03_0062 | 119,879 | 15,609 |
| District 9, Sumner County, Tennessee | DP03_0062 | 118,627 | 10,899 |
| District 25, Wilson County, Tennessee | DP03_0062 | 118,575 | 17,512 |
| District 7, Sumner County, Tennessee | DP03_0062 | 118,463 | 8,557 |
| District 6, Robertson County, Tennessee | DP03_0062 | 117,328 | 14,420 |
| District 2, Rutherford County, Tennessee | DP03_0062 | 113,618 | 8,331 |
| District 24, Davidson County, Tennessee | DP03_0062 | 112,813 | 9,455 |
| District 8, Wilson County, Tennessee | DP03_0062 | 111,045 | 21,662 |
| District 9, Rutherford County, Tennessee | DP03_0062 | 110,625 | 6,729 |
| District 4, Davidson County, Tennessee | DP03_0062 | 109,862 | 8,710 |
| District 3, Wilson County, Tennessee | DP03_0062 | 107,175 | 44,846 |
| District 8, Rutherford County, Tennessee | DP03_0062 | 106,781 | 8,523 |
| District 18, Wilson County, Tennessee | DP03_0062 | 106,590 | 11,693 |
| District 11, Williamson County, Tennessee | DP03_0062 | 106,331 | 10,348 |
| District 14, Wilson County, Tennessee | DP03_0062 | 105,610 | 12,378 |
| District 20, Rutherford County, Tennessee | DP03_0062 | 105,019 | 9,853 |
| District 23, Wilson County, Tennessee | DP03_0062 | 103,665 | 13,285 |
| District 11, Wilson County, Tennessee | DP03_0062 | 102,989 | 24,010 |
| District 3, Rutherford County, Tennessee | DP03_0062 | 102,465 | 26,412 |
| District 3, Cheatham County, Tennessee | DP03_0062 | 102,431 | 17,772 |
| District 6, Sumner County, Tennessee | DP03_0062 | 101,854 | 8,805 |
| District 6, Davidson County, Tennessee | DP03_0062 | 100,752 | 12,611 |
| District 12, Wilson County, Tennessee | DP03_0062 | 100,646 | 16,719 |
| District 11, Sumner County, Tennessee | DP03_0062 | 100,338 | 7,125 |
| District 6, Rutherford County, Tennessee | DP03_0062 | 99,858 | 6,412 |
| District 10, Rutherford County, Tennessee | DP03_0062 | 99,400 | 12,412 |
| District 13, Wilson County, Tennessee | DP03_0062 | 99,327 | 8,166 |
| District 18, Davidson County, Tennessee | DP03_0062 | 98,456 | 16,437 |
| District 1, Williamson County, Tennessee | DP03_0062 | 98,165 | 11,764 |
| District 8, Robertson County, Tennessee | DP03_0062 | 98,009 | 12,978 |
| District 6, Cheatham County, Tennessee | DP03_0062 | 96,888 | 7,927 |
| District 4, Robertson County, Tennessee | DP03_0062 | 96,786 | 11,251 |
| District 3, Robertson County, Tennessee | DP03_0062 | 96,330 | 13,669 |
| District 5, Cheatham County, Tennessee | DP03_0062 | 95,888 | 12,062 |
| District 6, Wilson County, Tennessee | DP03_0062 | 95,784 | 16,887 |
| District 1, Wilson County, Tennessee | DP03_0062 | 93,707 | 21,783 |
| District 12, Sumner County, Tennessee | DP03_0062 | 93,286 | 3,620 |
| District 33, Davidson County, Tennessee | DP03_0062 | 91,426 | 9,273 |
| District 3, Sumner County, Tennessee | DP03_0062 | 91,352 | 9,049 |
| District 2, Cheatham County, Tennessee | DP03_0062 | 91,066 | 13,173 |
| District 1, Rutherford County, Tennessee | DP03_0062 | 90,670 | 16,549 |
| District 22, Davidson County, Tennessee | DP03_0062 | 90,448 | 8,706 |
| District 12, Davidson County, Tennessee | DP03_0062 | 90,183 | 11,477 |
| District 19, Rutherford County, Tennessee | DP03_0062 | 89,030 | 4,746 |
| District 15, Rutherford County, Tennessee | DP03_0062 | 87,321 | 12,357 |
| District 13, Rutherford County, Tennessee | DP03_0062 | 85,947 | 14,167 |
| District 1, Davidson County, Tennessee | DP03_0062 | 85,926 | 6,963 |
| District 1, Robertson County, Tennessee | DP03_0062 | 85,805 | 8,217 |
| District 7, Davidson County, Tennessee | DP03_0062 | 84,268 | 11,060 |
| District 22, Wilson County, Tennessee | DP03_0062 | 84,191 | 13,790 |
| District 8, Sumner County, Tennessee | DP03_0062 | 83,520 | 8,772 |
| District 11, Robertson County, Tennessee | DP03_0062 | 83,413 | 23,697 |
| District 5, Davidson County, Tennessee | DP03_0062 | 83,094 | 6,483 |
| District 5, Robertson County, Tennessee | DP03_0062 | 83,030 | 12,188 |
| District 7, Robertson County, Tennessee | DP03_0062 | 82,401 | 13,032 |
| District 15, Wilson County, Tennessee | DP03_0062 | 81,792 | 20,253 |
| District 4, Cheatham County, Tennessee | DP03_0062 | 81,389 | 10,957 |
| District 9, Wilson County, Tennessee | DP03_0062 | 80,000 | 26,506 |
| District 10, Robertson County, Tennessee | DP03_0062 | 78,977 | 12,903 |
| District 1, Sumner County, Tennessee | DP03_0062 | 78,900 | 7,341 |
| District 2, Robertson County, Tennessee | DP03_0062 | 78,862 | 12,141 |
| District 7, Rutherford County, Tennessee | DP03_0062 | 78,531 | 7,730 |
| District 26, Davidson County, Tennessee | DP03_0062 | 78,460 | 5,564 |
| District 19, Davidson County, Tennessee | DP03_0062 | 78,125 | 7,880 |
| District 31, Davidson County, Tennessee | DP03_0062 | 77,287 | 7,392 |
| District 19, Wilson County, Tennessee | DP03_0062 | 76,788 | 15,138 |
| District 4, Rutherford County, Tennessee | DP03_0062 | 76,541 | 10,884 |
| District 1, Cheatham County, Tennessee | DP03_0062 | 76,212 | 17,842 |
| District 10, Sumner County, Tennessee | DP03_0062 | 76,196 | 12,634 |
| District 11, Davidson County, Tennessee | DP03_0062 | 75,655 | 6,932 |
| District 2, Sumner County, Tennessee | DP03_0062 | 75,380 | 10,336 |
| District 4, Sumner County, Tennessee | DP03_0062 | 75,335 | 14,218 |
| District 20, Davidson County, Tennessee | DP03_0062 | 73,175 | 11,878 |
| District 17, Davidson County, Tennessee | DP03_0062 | 73,141 | 6,662 |
| District 15, Davidson County, Tennessee | DP03_0062 | 72,275 | 5,800 |
| District 24, Wilson County, Tennessee | DP03_0062 | 72,031 | 19,997 |
| District 12, Rutherford County, Tennessee | DP03_0062 | 71,907 | 10,010 |
| District 5, Rutherford County, Tennessee | DP03_0062 | 71,875 | 10,610 |
| District 16, Davidson County, Tennessee | DP03_0062 | 70,152 | 8,513 |
| District 29, Davidson County, Tennessee | DP03_0062 | 69,010 | 10,318 |
| District 18, Rutherford County, Tennessee | DP03_0062 | 68,258 | 5,976 |
| District 8, Davidson County, Tennessee | DP03_0062 | 68,184 | 12,467 |
| District 14, Davidson County, Tennessee | DP03_0062 | 67,390 | 5,605 |
| District 17, Wilson County, Tennessee | DP03_0062 | 67,079 | 12,356 |
| District 3, Davidson County, Tennessee | DP03_0062 | 66,981 | 9,922 |
| District 28, Davidson County, Tennessee | DP03_0062 | 66,823 | 7,833 |
| District 21, Rutherford County, Tennessee | DP03_0062 | 66,551 | 9,535 |
| District 27, Davidson County, Tennessee | DP03_0062 | 65,330 | 7,174 |
| District 32, Davidson County, Tennessee | DP03_0062 | 65,091 | 4,317 |
| District 11, Rutherford County, Tennessee | DP03_0062 | 63,170 | 10,499 |
| District 10, Davidson County, Tennessee | DP03_0062 | 63,090 | 4,419 |
| District 13, Davidson County, Tennessee | DP03_0062 | 62,289 | 6,700 |
| District 21, Wilson County, Tennessee | DP03_0062 | 62,271 | 11,609 |
| District 16, Rutherford County, Tennessee | DP03_0062 | 61,545 | 1,395 |
| District 7, Wilson County, Tennessee | DP03_0062 | 61,486 | 10,944 |
| District 9, Robertson County, Tennessee | DP03_0062 | 61,273 | 5,834 |
| District 5, Sumner County, Tennessee | DP03_0062 | 57,871 | 12,109 |
| District 2, Davidson County, Tennessee | DP03_0062 | 57,200 | 7,122 |
| District 30, Davidson County, Tennessee | DP03_0062 | 53,796 | 2,660 |
| District 21, Davidson County, Tennessee | DP03_0062 | 53,163 | 4,246 |
| District 9, Davidson County, Tennessee | DP03_0062 | 51,290 | 3,883 |
| District 12, Robertson County, Tennessee | DP03_0062 | 50,069 | 7,812 |
| District 20, Wilson County, Tennessee | DP03_0062 | 48,012 | 10,259 |
| District 17, Rutherford County, Tennessee | DP03_0062 | 45,955 | 7,601 |