I want to use specific colors for factor levels in a ggplot, and i pass these to scale_fill_manual.
However, after I filter the data set to remove some factor levels, the colors values shift and are no longer aligned as before.
library(ggplot2) library(dplyr) mod.cars <- mtcars %>% mutate(gear = as.factor(gear)) # just for demo purposes # the colors i want to be assigned to the specific factor levels gear.cols <- c("red", "green", "blue") ggplot(mod.cars, aes(x=hp, fill=gear)) + geom_boxplot() + scale_fill_manual(values=gear.cols)
This graph creates 3 boxes, where gear=3 is red, gear=4 is green, and gear=5 is blue.
This is what I want.
If I filter out a factor level and recreate the plot,
mod.cars %>% filter(gear %in% c(4,5)) %>% ggplot(aes(x=hp, fill=gear)) + geom_boxplot() + scale_fill_manual(values=gear.cols)
gear=4 is now red, and gear=5 is now green.
Basically the data set doesn't seem to recognize that
levels(gear) should still contain 3, even if there is no data now, there was a gear level=3 before the filter.
How can I maintain the assigned colors for all factor levels, on a subset?