Skip to content

Instantly share code, notes, and snippets.

@pumphandle
Created August 5, 2019 19:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pumphandle/5f48be82f41c5e9b2fc1e2dcba87b7d1 to your computer and use it in GitHub Desktop.
Makes a simple choropleth map using custom shapefile
library(tidycensus)
library(tidyverse)
library(rgdal)
census_api_key("<your api key here>", overwrite=T, install="TRUE")
uspop <- get_acs(geography = "state", variables = c(pop = "B06012_001"), year=2017)
uspov <- get_acs(geography = "state", variables = c(pov="B06012_002"), year=2017)
uspovrate <- uspov$estimate/uspop$estimate
us <- cbind(uspop, uspovrate)
us$stabbr <- state.abb[match(us$NAME,state.name)]
us$stabbr[9] <- "DC"
us$stabbr[52] <- "PR"
us <- select(us, -variable, -estimate, -moe)
us$quartile <- with(us, cut(uspovrate,
breaks=quantile(uspovrate, probs=seq(0,1, by=0.25), na.rm=TRUE),
include.lowest=TRUE))
shape <- readOGR(dsn = "C:/fpb/qgis", layer = "mon4")
map1 <- merge(shape,us, by="stabbr")
map1$id <- as.character(0:57)
map2 <- fortify(map1)
map2b <- left_join(map2,map1@data, by="id")
ggplot(map2b, aes(map_id = id)) +
geom_map(aes(fill = quartile), map = map2b) +
expand_limits(x = map2b$long, y = map2b$lat) +
scale_fill_brewer(palette="Greens", na.value="gray60") +
guides(fill = guide_legend(title = "Poverty Rate, 2013-2017")) +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
panel.background = element_rect(fill="gray45"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment