Created
November 15, 2020 22:26
Code to create a map of change in US county population, 2013 - 2018, for the 30 Day Map Challenge
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(ggplot2) | |
library(dplyr) | |
library(tigris) | |
library(tidycensus) | |
abbr <- state.abb[-c(2, 11)] | |
pop2018 <- vector("list", length(abbr)) | |
names(pop2018) <- abbr | |
for (i in seq_len(length(pop2018))) { | |
pop2018[[i]] <- get_acs("county", | |
"B01003_001", | |
geometry = TRUE, | |
state = names(pop2018)[[i]] | |
) | |
} | |
state_2018 <- do.call(rbind, pop2018) | |
pop2013 <- vector("list", length(abbr)) | |
names(pop2013) <- abbr | |
for (i in seq_len(length(pop2013))) { | |
pop2013[[i]] <- get_acs("county", | |
"B01003_001", | |
year = 2013, | |
geometry = TRUE, | |
state = names(pop2013)[[i]] | |
) | |
} | |
state_2013 <- do.call(rbind, pop2013) | |
county_line <- counties(abbr, TRUE) | |
state_2018 %>% | |
rename(est2018 = estimate) %>% | |
select(GEOID, est2018, geometry) %>% | |
left_join(state_2013 %>% | |
rename(est2013 = estimate) %>% | |
select(GEOID, est2013) %>% | |
sf::st_set_geometry(NULL)) %>% | |
mutate(value = (est2018 - est2013) / est2013) %>% | |
arrange(value) %>% | |
mutate(idx = row_number()) %>% | |
ggplot() + | |
geom_sf(aes(fill = idx), color = NA) + | |
geom_sf(data = county_line, | |
fill = NA, | |
color = "#F0F0F0", | |
size = 0.03, | |
alpha = 0.05) + | |
scale_fill_gradient2(low = "#40004b", high = "#00441b", midpoint = 1698) + | |
coord_sf() + | |
theme_void() %+replace% | |
theme( | |
legend.position = "none", | |
plot.background = element_rect(fill = "#2c2c2c") | |
) | |
ggsave("22_movement.png", width = 17, height = 9, dpi = 600) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment