JFD
JFD

Reputation: 339

Overlay State Outlines on County Plot using urbanmapr in R

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())

produces the following image: County Chloropleth made with urbanmapr

Thanks for your help

jfd118

Upvotes: 0

Views: 760

Answers (1)

Edward
Edward

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())

enter image description here

Upvotes: 2

Related Questions