Skip to content

Instantly share code, notes, and snippets.

@walkerke
Created May 12, 2022 17:01
Show Gist options
  • Save walkerke/4bd8f5efbd71bb14e5238b40af680285 to your computer and use it in GitHub Desktop.
Save walkerke/4bd8f5efbd71bb14e5238b40af680285 to your computer and use it in GitHub Desktop.
library(tidycensus)
library(ggplot2)
library(mapboxapi)
library(sf)
options(tigris_use_cache = TRUE)
# Get the 2020 Census data
# Transform to a projected coordinate reference system
# to improve performance
twin_cities_race <- get_decennial(
geography = "tract",
state = "MN",
county = c("Hennepin", "Ramsey", "Anoka", "Dakota",
"Scott", "Carver", "Washington"),
variables = c(
Hispanic = "P2_002N",
White = "P2_005N",
Black = "P2_006N",
Native = "P2_007N",
Asian = "P2_008N"
),
year = 2020,
geometry = TRUE
) %>%
st_transform(6505)
# Get the basemap (requires a Mapbox access token)
# https://walker-data.com/mapboxapi/reference/mb_access_token.html
basemap <- layer_static_mapbox(
location = twin_cities_race,
style_id = "light-v9",
username = "mapbox"
)
# Generate the dots (faster)
twin_cities_dots <- as_dot_density(
twin_cities_race,
value = "value",
values_per_dot = 200,
group = "variable"
)
# Generate the dots (slower, but more accurate)
twin_cities_dots_erase <- as_dot_density(
twin_cities_race,
value = "value",
values_per_dot = 200,
group = "variable",
erase_water = TRUE,
area_threshold = 0.95
)
# Map it out
ggplot() +
basemap +
geom_sf(
data = twin_cities_dots_erase,
aes(color = variable),
shape = "."
) +
theme_void() +
labs(color = "Race/ethnicity,\n2020 Census",
caption = "Seven-county Twin Cities area | tidycensus R package | 1 dot = 200 people") +
scale_color_brewer(palette = "Set1") +
guides(color = guide_legend(override.aes = list(shape = 16)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment