I have a lot of categorical variables that are going into a single graph, which is split on a particular status. Something like this, but with many more groups
dat <- as.data.table(cbind(iris, Status = rep(c("High", "Low"), 75)))
dat <- rbind(dat, data.frame(Petal.Width = sample(iris$Petal.Width, 30, replace = T),
Species = "Control",
Status = "Control"), fill = T)
ggplot(dat, aes(x = Species,y = Petal.Width, fill = Status))
geom_boxplot(position = position_dodge(width = 0.9))
scale_fill_manual(values = c("red", "pink",
"red", "pink",
"blue", "slateblue", "grey"))
I am trying to colour the boxplots independent of the fill status I've used to create the dodged boxplots, but you can see in the code above, scale_fill_manual will only take 3 colours.
I would like to manually overwrite the colours independent of the grouping aesthetics, while maintaining the boxplot split between "high" and "low".
Assume setosa and versicolor have something in common (colors red and pink), while virginica is its own category (blue and slate blue), and control is a special case (grey).
Is there any way to colour each bar separately?
CodePudding user response:
We can use interaction
for the fill
parameter, then we can color each box plot with scale_fill_manual
.
library(ggplot2)
ggplot(dat, aes(x = Species, y = Petal.Width, fill = interaction(Status,Species)))
geom_boxplot(position = position_dodge(width = 0.9))
scale_fill_manual(values = c("red", "pink",
"red", "pink",
"blue", "slateblue", "grey"))