Reputation: 339
I'm trying to add an outline of US states to a choropleth of county data using ubrbanmapr. I can either plot state outlines or the county choropleth, but not the county choropleth with state outlines. Any guidance is appreciated.
The code:
library(urbnmapr)
library(ggplot2)
library(dplyr)
# Obtain county polygon data
counties_sf <- get_urbn_map(map = "counties", sf = TRUE)
# Assign random values of data to each count
counties_sf$value = runif(length(counties_sf$county_fips), min=-1.0, max=1.0)
# Remove AK and HI - lower 48 only
counties_sf <- counties_sf[!(counties_sf$state_abbv %in% c("HI","AK")),]
# Plot county level data
counties_sf %>%
ggplot() +
# Overlay State Outlines
geom_polygon(data = urbnmapr::states, mapping = aes(long, lat, group = group),
fill = NA, color = "black", size = 0.25) +
# Plot county data and fill with value
geom_sf(mapping = aes(fill = value), color = NA) +
# Remove grid lines from plot
coord_sf(datum = NA) +
labs(fill = "Random Data") +
scale_fill_gradient2(low='blue', high='red') +
theme_bw() +
theme(
# Hide panel borders and remove grid lines
panel.border = element_blank())
Thanks for your help
jfd118
Upvotes: 0
Views: 760
Reputation: 18683
Don't use geom_polygon, add another geom_sf.
#devtools::install_github("UrbanInstitute/urbnmapr")
library(urbnmapr)
library(ggplot2)
library(dplyr)
# Obtain county polygon data
states_sf <- get_urbn_map(map = "states", sf = TRUE)
counties_sf <- get_urbn_map(map = "counties", sf = TRUE)
# Assign random values of data to each count
set.seed(1234)
counties_sf$value = runif(length(counties_sf$county_fips), min=-1.0, max=1.0)
# Plot county level data
ggplot() +
# Plot county data and fill with value
geom_sf(data=counties_sf, mapping = aes(fill = value), color = NA) +
# Overlay State Outlines
geom_sf(data = states_sf, fill = NA, color = "black", size = 0.25) +
# Remove grid lines from plot
coord_sf(datum = NA) +
labs(fill = "Random Data") +
scale_fill_gradient2(low='blue', high='red') +
theme_bw() +
theme(
# Hide panel borders and remove grid lines
panel.border = element_blank())
Upvotes: 2