Skip to content
Course Notes: Analyzing US Census Data in R
First, we need to install and load the tidycensus package.
install.packages('tidycensus')
library(tidycensus)Visualizing margins of error (MOE)
# Write and run code here
# Request median household income data
maine_inc <- get_acs(geography = "county",
variables = c(hhincome = "B19013_001"),
state = "ME")# Generate horizontal error bars with dots
ggplot(maine_inc, aes(x = estimate, y = NAME)) +
geom_errorbarh(aes(xmin = estimate - moe, xmax = estimate + moe)) +
geom_point()# Remove unnecessary content from the county's name
maine_inc2 <- maine_inc %>%
mutate(NAME = str_replace(NAME, " County, Maine", ""))
# Build a margin of error plot incorporating your modifications
ggplot(maine_inc2, aes(x = estimate, y = reorder(NAME, estimate))) +
geom_errorbarh(aes(xmin = estimate - moe, xmax = estimate + moe)) +
geom_point(size = 3, color = "darkgreen") +
theme_grey(base_size = 14) +
labs(title = "Median household income",
subtitle = "Counties in Maine",
x = "ACS estimate (bars represent margins of error)",
y = "") +
scale_x_continuous(labels = scales::dollar)US Census geographic data
install.packages('tigris')
library(tigris)# Get a counties dataset for Colorado and plot it
co_counties <- counties(state = "CO")
plot(co_counties)# Get a Census tracts dataset for Denver County, Colorado and plot it
denver_tracts <- tracts(state = "CO", county = "Denver")
plot(denver_tracts)# Plot area water features for Lane County, Oregon
lane_water <- area_water(state = "OR", county = "Lane")
plot(lane_water)# Plot primary & secondary roads for the state of New Hampshire
nh_roads <- primary_secondary_roads(state = "NH")
plot(nh_roads)TIGER/Line and cartographic boundary files
# Get a counties dataset for Michigan
mi_tiger <- counties("MI")
# Get the equivalent cartographic boundary shapefile
mi_cb <- counties("MI", cb = TRUE)
# Overlay the two on a plot to make a comparison
plot(mi_tiger)
plot(mi_cb, add = TRUE, border = "red")# Get data from tigris as simple features
options(tigris_class = "sf")
# Get countries from Colorado and view the first few rows
colorado_sf <- counties("CO")
head(colorado_sf)
# Plot its geometry column
plot(colorado_sf$geometry)