Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created December 27, 2024 22:47
Show Gist options
  • Save walkerke/6331f17715649940f03cdbe60a8584c2 to your computer and use it in GitHub Desktop.
Save walkerke/6331f17715649940f03cdbe60a8584c2 to your computer and use it in GitHub Desktop.
library(tidycensus)
library(tidyverse)
library(RColorBrewer)
natchg <- get_estimates(
geography = "state",
variables = "RNATURALCHG",
vintage = 2024
)
custom_palette <- c(rev(brewer.pal(5, "Reds")), "#FFFFFF", brewer.pal(5, "Greens"))
max_abs_value <- max(abs(natchg$value))
ggplot(natchg, aes(x = reorder(NAME, value), y = value, fill = value)) +
geom_col(width = 0.7) +
geom_text(aes(label = NAME,
x = reorder(NAME, value),
y = 0,
hjust = ifelse(value >= 0, 1, 0)),
size = 3, color = "black", nudge_y = ifelse(natchg$value >= 0, -0.05, 0.05)) +
geom_text(aes(label = sprintf("%.2f", value),
hjust = ifelse(value >= 0, -0.1, 1.1)),
size = 3, color = "black", position = position_dodge(0.7)) +
coord_flip() +
scale_fill_gradientn(colors = custom_palette,
limits = c(-max_abs_value, max_abs_value)) +
scale_y_continuous(limits = c(-max_abs_value - 0.5, max_abs_value + 0.5),
breaks = seq(-ceiling(max_abs_value), ceiling(max_abs_value), by = 1)) +
labs(title = "Rate of Natural Change by State (2023-2024)",
x = "",
y = "Natural change (per 1000 residents)",
caption = "2024 US Census Bureau Population Estimates | tidycensus R package") +
theme_minimal() +
theme(legend.position = "none",
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
plot.title = element_text(face = "bold"),
plot.subtitle = element_text(size = 9, color = "gray30"),
plot.caption = element_text(size = 8, color = "gray50", hjust = 1)) +
geom_vline(xintercept = 0, linetype = "dashed", color = "gray50")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment