I'm working on a map that uses the ggplot scale_fill_stepn function to color a US counties map with unequal breaks. The resulting legend spaces the color scale according to the relative distance between the breaks. How do I make the blocks of color in the legend equally spaced?
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
counties_sf$value = runif(length(counties_sf$county_fips), min=-3.0, max=3.0)
# Remove AK and HI - lower 48 only
states_sf <- states_sf[!(states_sf$state_abbv %in% c("HI","AK")),]
counties_sf <- counties_sf[!(counties_sf$state_abbv %in% c("HI","AK")),]
# Plot county level data with a discrete legend
data_levels <- c(-3,-1.5, -0.8, -0.5, -0.25,-0.1,0.1,0.25,0.5,.8,1.5,3)
level_colors <- c('#aa411c','#bf662e','#d59042','#ecb554','#fddc67','#FFFF73','#cbff66','#87f345','#00e601','#00b300','#009a00','#007b00')
length(data_levels)
length(level_colors)
counties_sf %>%
ggplot() +
# Overlay State Outlines
# Plot county data and fill with value
geom_sf(mapping = aes(fill = value), color = NA) +
geom_sf(data = states_sf, fill = NA, color = "black", size = 0.25) +
# Remove grid lines from plot
coord_sf(datum = NA) +
scale_fill_stepsn(breaks=data_levels, colors=level_colors, limits=c(-3,3)) +
labs(title='This Data is Completely Random',
fill='Deviation from Trend') +
theme_map() +
theme(legend.position = "bottom",
legend.key.width=unit(1.5,"cm"),
legend.box.background = element_rect(color="black", size=2),
legend.title = element_text(face = "bold"),
legend.spacing = unit(1,"cm"),
legend.justification = "center",
plot.title=element_text(hjust=0.5)) +
guides(fill = guide_colourbar(title.position="top", title.hjust = 0.5))
