I am plotting a group of "treatment" counties, using usmap::plot_usmap(), such that treatment=1 for the identified counties an 0 otherwise. I would like the legend to reflect the fact that the variable is discrete (0/1) rather than show a continuous scale of colors? My dataset has 2 variables: fips and treatment.
My code is:
library(usmap)
library(ggplot2)
plot_usmap(regions = "county", data=data, values = "treatment",color="grey")+
theme(panel.background = element_rect(colour = "black"))+
scale_fill_gradient(low = "white", high = "blue",name = "treatment",
breaks=c(0,1), limits = c(0, 1)) +
theme(legend.position = "right")
You have to convert treatment to a factor
or character
. Colors can then be set via scale_fill_manual
. Using some random example data
try this:
library(usmap)
library(ggplot2)
library(dplyr, warn = FALSE)
# example data
set.seed(42)
data <- usmapdata::fips_data(regions = "counties") %>%
select(fips) %>%
mutate(treatment = sample(c(0, 1), nrow(.), replace = TRUE))
# Convert treatment to factor
data <- mutate(data, treatment = factor(treatment))
plot_usmap(
regions = "county", data = data,
values = "treatment", color = "grey"
) +
theme(panel.background = element_rect(colour = "black")) +
scale_fill_manual(
values = c(`0` = "white", `1` = "blue"),
name = "treatment"
) +
theme(legend.position = "right")