Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created May 26, 2022 17:30
Show Gist options
  • Save walkerke/0e0a21eecfccd6d0bf0bc60213e2f598 to your computer and use it in GitHub Desktop.
Save walkerke/0e0a21eecfccd6d0bf0bc60213e2f598 to your computer and use it in GitHub Desktop.
library(tidycensus)
library(tidyverse)
# Get the data
income_data <- get_acs(
geography = "county",
variables = "B19013_001",
state = "ME",
year = 2020,
geometry = TRUE
)
# Let's take a look at the data structure
income_data
# A first plot
ggplot(income_data, aes(x = estimate, y = NAME)) +
geom_point()
# Let's step through some improvements:
library(scales)
ggplot(income_data, aes(x = estimate, y = reorder(NAME, estimate))) +
geom_errorbar(aes(xmin = estimate - moe, xmax = estimate + moe)) +
geom_point(size = 3, color = "darkgreen") +
theme_minimal(base_size = 12.5) +
labs(title = "Median household income",
subtitle = "Counties in Maine",
x = "2016-2020 ACS estimate",
y = "") +
scale_x_continuous(labels = label_dollar()) +
scale_y_discrete(labels = ~word(.x, sep = " County"))
# Want a map? Change the geom!
ggplot(income_data, aes(fill = estimate)) +
geom_sf() +
theme_void(base_size = 12.5) +
labs(fill = "2016-2020\nACS estimate") +
scale_fill_distiller(palette = "Greens", direction = 1,
labels = label_dollar())
# What if I don't know much about Maine?
# R can bring charts and technologies together!
library(ggiraph)
library(patchwork)
income_map <- ggplot(income_data, aes(fill = estimate)) +
geom_sf_interactive(aes(data_id = GEOID)) +
scale_fill_distiller(palette = "Greens",
direction = 1,
guide = "none") +
theme_void()
income_plot <- ggplot(income_data, aes(x = estimate,
y = reorder(NAME, estimate),
fill = estimate)) +
geom_errorbar(aes(xmin = estimate - moe, xmax = estimate + moe)) +
geom_point_interactive(color = "black", size = 4, shape = 21,
aes(data_id = GEOID)) +
scale_fill_distiller(palette = "Greens", direction = 1,
labels = label_dollar()) +
scale_x_continuous(labels = label_dollar()) +
scale_y_discrete(labels = ~word(.x, sep = " County")) +
labs(title = "Household income by county in Maine",
subtitle = "2016-2020 American Community Survey",
y = "",
x = "ACS estimate (bars represent margin of error)",
fill = "ACS estimate") +
theme_minimal(base_size = 14)
girafe(ggobj = income_map + income_plot, width_svg = 10, height_svg = 5) %>%
girafe_options(opts_hover(css = "fill:cyan;"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment