Created
June 23, 2022 14:32
-
-
Save walkerke/be99b26e818d6a9d32bf71dc617569be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidycensus) | |
library(tidyverse) | |
us_county_density <- get_decennial( | |
geography = "county", | |
variables = "P1_001N", | |
year = 2020, | |
geometry = TRUE, | |
keep_geo_vars = TRUE | |
) | |
us_county_density %>% | |
mutate(density = value / (ALAND / 2589988.11)) %>% | |
tigris::shift_geometry() %>% | |
ggplot(aes(fill = density)) + | |
geom_sf(color = NA) + | |
theme_void(base_size = 11) + | |
scale_fill_viridis_c(trans = "log10") + | |
labs(title = "Population density by county", | |
subtitle = "2020 US Census", | |
fill = "Persons / sq mi", | |
caption = "@kyle_e_walker | tidycensus R package") + | |
theme(plot.margin = unit(rep(0.5, 4), "cm")) | |
options(scipen = 999) | |
dallas_density <- get_decennial( | |
geography = "tract", | |
state = "TX", | |
county = "Dallas", | |
variables = "P1_001N", | |
year = 2020, | |
geometry = TRUE, | |
keep_geo_vars = TRUE | |
) %>% | |
mutate(density = value / (ALAND / 2589988.11)) | |
mapview::mapview(dallas_density, zcol = "density", | |
layer.name = "Population density<br/>in Dallas County<br/>(people/sq mi)") | |
# ACS example: population density vs. income in Illinois | |
illinois <- get_acs( | |
geography = "tract", | |
variables = c(total_pop = "B01003_001", | |
median_income = "B19013_001"), | |
state = "IL", | |
geometry = TRUE, | |
keep_geo_vars = TRUE, | |
output = "wide" | |
) %>% | |
mutate(density = total_popE / (ALAND / 2589988.11)) | |
ggplot(illinois, aes(x = density, y = median_incomeE)) + | |
geom_point(alpha = 0.5) + | |
geom_smooth() + | |
theme_minimal() + | |
scale_x_log10() + | |
scale_y_continuous(labels = scales::label_dollar()) + | |
labs(title = "Relationship between tract density and median household income", | |
subtitle = "Census tracts in Illinois, 2016-2020 ACS", | |
x = "Population density (people / square mile)", | |
y = "Median household income", | |
caption = "@kyle_e_walker | tidycensus R package") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The section starting on line 27 (dallas_density) gives an error 'Invalid argument name and cannot create file. Any ideas?