Skip to content

Instantly share code, notes, and snippets.

@ryanpeek
Created January 28, 2022 17:12
Show Gist options
  • Save ryanpeek/89055211513f458949a45037a4a622c9 to your computer and use it in GitHub Desktop.
Save ryanpeek/89055211513f458949a45037a4a622c9 to your computer and use it in GitHub Desktop.
making USA state composite map w tigris
# us states maps for equal area or otherwise
# best projections for Eq Area is probably Albers Eq Area (CRS 102003)
# for just display, can use a conformal albers or mercator (4326)
# libraries
library(tidyverse)
library(sf)
library(tigris)
options(tigris_use_cache = TRUE)
library(tidycensus)
# get USA states from tigris, cb=TRUE downloads simpler version
# shift geometry handy for shifting all to same proj (see tigris help)
# places AK/HI/PR below USA (default)
us_states <- states(cb = TRUE, resolution = "20m") %>%
shift_geometry()
# Shift but preserve area (crs 102003), places AK/HI/PR below USA
us_states_eqarea <- states(cb = TRUE, resolution = "20m") %>%
shift_geometry(preserve_area = TRUE)
# Shift and rescale but position AK/HI/PR outside the continental US
us_states_outside <- states(cb = TRUE, resolution = "20m") %>%
shift_geometry(position = "outside")
# Plot All ----------------------------------------------------------------
ggplot() +
geom_sf(data = us_states, fill=NA, color="black", size=1) +
geom_sf(data = us_states_eqarea, fill=NA, color="orange", size=0.7) +
geom_sf(data = us_states_outside, fill=NA, color="blue", size=0.2) +
theme_void()
# Fancy Map ---------------------------------------------------------------
# Shift a dataset obtained outside tigris and make a map
income_by_metro <- get_acs(
geography = "cbsa",
variables = "B01002_001",
geometry = TRUE
) %>%
shift_geometry()
ggplot() +
geom_sf(data = income_by_metro, aes(fill = estimate), color = NA) +
geom_sf(data = us_states, fill = NA, color = "black", size = 0.1) +
scale_fill_viridis_c() +
theme_void(base_size = 16) +
labs(title = "Median age by CBSA, 2015-2019 ACS",
fill = "ACS estimate ",
caption = "Note: Alaska, Hawaii, and Puerto Rico are shifted and not to scale.") +
theme(plot.title = element_text(hjust = 0.5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment