This is my first question here and I'm a beginner with R.
I've looked at similar questions including:
- Assign stable colors to ggplot when reordering and subsetting
- How to assign colors to categorical variables in ggplot2 that have stable mapping?
The first one, "Assign stable colors to ggplot when"... etc, is really really close to what I want to do, but not quite. Let me explain using the mtcars dataset as an example.
Let's say I am preparing some figures for Mazda. Every time my audience sees Mazda RX4 on a figure I want it to be pink AND if Mazda isn't included on the figure (maybe I'm looking at only competitors for a specific figure) I don't want any of the other cars to show up as pink. Basically, I want to tell R: "If Mazda RX4 is in the dataset, make it pink. If Mazda RX4 is not in the dataset, don't use pink at all."
Here's where my code stands right now (thanks to the questions I linked above):
data <- mtcars %>%
rownames_to_column() %>%
rowid_to_column() %>%
mutate(rowname = reorder(rowname, mpg))
fullplot <- data %>%
ggplot(aes(rowname, mpg, fill = rowname, color = rowname)) +
geom_col()+
coord_flip()
fullplot
fullplot yields the following: full barchart, all cars
Then, I made a reduced version with just the two Mazdas:
reducedplot <- fullplot %+% droplevels(filter(data, rowid < 3))
Finally, a third version that includes the two Mazdas and another car:
reducedplot2 <- fullplot %+% droplevels(filter(data, rowid < 4))
Now that I've got my three example figures established I have assigned colors to what I'm interested in, and I call it mazda_constants:
mazda_constants <- c("Mazda RX4" = "hotpink1", "Mazda RX4 Wag" = "deeppink3")
reducedplot +
scale_fill_manual(values = mazda_constants) +
scale_color_manual(values = mazda_constants)
My issue is that this only works when I use my reducedplot that ONLY contains Mazdas. If I try to apply it to fullplot or even to reducedplot2, I get this error:
reducedplot2 +
scale_fill_manual(values + mazda_constants) +
scale_color_manual(values = mazda_constants)
Error: Insufficient values in manual scale. 3 needed but only 2 provided.
I understand why this is happening, and I understand R is doing what I'm telling it to do, but I can't find a work-around. Is there a way to assign the color pink to Mazdas no matter what?
Please note that I am not able to upload more than one picture -- maybe due to my new-member status. I hope the code is clear enough to explain.