在箱线图中指定独立于映射美学的填充颜色(R ggplot)

Specifying fill color independent of mapping aesthetics in boxplot (R ggplot)

我有很多分类变量进入单个图表,该图表按特定状态拆分。类似这样,但有更多组

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"))

我正在尝试独立于我用来创建闪避箱线图的填充状态为箱线图着色,但您可以在上面的代码中看到,scale_fill_manual 只会采用 3 种颜色。

我想独立于分组美学手动覆盖颜色,同时保持“高”和“低”之间的箱线图分割。

假设 setosa 和 versicolor 有一些共同点(红色和粉红色),而 virginica 是它自己的类别(蓝色和石板蓝),而对照是一个特例(灰色)。

有什么方法可以分别为每个条形着色吗?

我们可以使用 interaction 作为 fill 参数,然后我们可以用 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"))