Reputation: 2439
Is there any automatic way of keeping the different colours that ggplot2 uses it doesn't matter if the a specific class is present or not in a given plot?
For the following problem:
library(ggplot2)
set.seed(100)
data <- data.frame(y=rnorm(100,2),class=sample(c("A","B","C"),100,rep=T),
stringsAsFactors=T)
output <- ggplot(data[which(data[,"class"] != "B"),],
aes_string(x="class", y="y", fill="class")) +
geom_boxplot() +
scale_x_discrete(limits=c("A","B","C"), "class", drop=F)
If I don't use the samples of class B, I get the following plot:
output <- ggplot(data,
aes_string(x="class", y="y", fill="class")) +
geom_boxplot() +
scale_x_discrete(limits=c("A","B","C"), "class", drop=F)
But I would like to keep the palette in the same way it looks if all the classes are present:
I know that I can put the palette manually, but I would like to know it I can force ggplot to take into account all the classes even though one of them is not present.
Upvotes: 0
Views: 392
Reputation: 132969
You already know how to do this:
ggplot(data[which(data[,"class"] != "B"),],
aes_string(x="class", y="y", fill="class")) +
geom_boxplot() +
scale_x_discrete(limits=c("A","B","C"), "class", drop=F) +
scale_fill_discrete(drop = F)
Upvotes: 1