Skip to content

Instantly share code, notes, and snippets.

@mikemahoney218
Created January 26, 2022 23:52
Show Gist options
  • Save mikemahoney218/40f76961366de751eeb961919c05ce30 to your computer and use it in GitHub Desktop.
Save mikemahoney218/40f76961366de751eeb961919c05ce30 to your computer and use it in GitHub Desktop.
Quick population map
library(sf)
library(tidycensus)
library(dplyr)
library(ggplot2)
options(tigris_use_cache = TRUE)
acs_pop <- do.call(
rbind,
lapply(
setdiff(state.abb, c("AK", "HI")),
\(x) get_acs(
geography = "block group",
variables = "B01003_001",
state = x,
year = 2019,
geometry = TRUE,
cache_table = TRUE
)
)
)
usa_pop <- acs_pop %>%
tidyr::drop_na() %>%
mutate(in_area = units::drop_units(st_area(.)) * 1e-6,
estimate = estimate / in_area)
plot_col <- "#F9F9F9"
usa_pop |>
mutate(class = case_when(
estimate > 10000 ~ 5,
estimate > 1000 ~ 4,
estimate > 100 ~ 3,
estimate > 10 ~ 2,
TRUE ~ 1
),
class = factor(class,
levels = 1:5,
labels = c(
"[0, 10]",
"(10, 100]",
"(100, 1,000]",
"(1,000, 10,000]",
"(10,000, +]"
))) |>
ggplot() +
geom_sf(aes(fill = factor(class)), color = NA) +
scico::scale_fill_scico_d(palette = "lajolla",
name = expression("Population per km"^2),
guide = guide_legend(title.position = "bottom"),
direction = -1) +
theme(axis.line = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
# https://fonts.google.com/specimen/Lato
text = element_text(family = "Lato", colour = "#191900"),
strip.background = element_blank(),
strip.text = element_text(size = 11),
legend.text = element_text(size = 9),
legend.title = element_text(hjust = 0, size = 12),
legend.background = element_blank(),
legend.spacing = unit(11, "pt"),
legend.margin = margin(0, 0, 0, 0),
legend.key = element_blank(),
legend.key.size = unit(1.1 * 12, "pt"),
legend.box.margin = margin(0, 0, 0, 0),
legend.box.background = element_blank(),
legend.box.spacing = unit(11, "pt"),
legend.position = "bottom",
panel.background = element_rect(fill = plot_col, color = plot_col),
plot.background = element_rect(fill = plot_col, color = plot_col),
legend.justification = c("center"),
legend.key.width = unit(1.7 * 12, "pt"))
ggsave("usa_population.png", width = 16, height = 10, units = "in")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment