如何使用 scale_fill_manual 手动定义条形图颜色

How to use scale_fill_manual to manually define bar plot colors

我正在使用 ggplot2 完成我的数据集的表示,为了清楚起见,我需要一个违反标准 ggplot2“逻辑”的着色方案。 下面是一个假数据集,向您展示我的本质需求:

df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                  dose=rep(c("D0.5", "D1", "D2"),2),
                  len=c(6.8, 15, 33, 4.2, 10, 29.5))
head(df2)

supp dose  len
1   VC D0.5  6.8
2   VC   D1 15.0
3   VC   D2 33.0
4   OJ D0.5  4.2
5   OJ   D1 10.0
6   OJ   D2 29.5

这是我在下面的情节中使用的基本表示:

ggplot(data=df2, aes(x=dose, y=len, fill=supp)) +
  geom_bar(stat="identity", position=position_dodge())

我需要的是仅对 VC 系列应用个性化调色板 (myPalette <- c("#05eb92", "#119da4", "#ffc857")),同时将 OC 系列着色为黑色。下面是我需要的预期情节。我知道这种着色方案违背了 ggplot2 “逻辑”,但我想知道是否有一种简单的方法可以将其应用于我的需要。谢谢。

我会在您的输入 df2 中为 ggplot fill 美学创建一个 dummy 变量。这里的“-999”指的是“OJ”,会变成黑色。

我还更新了您的 myPalette 以在其中包含黑色,并且 setNames 也更新了它,以便只有“-999”具有相应的“黑色”值。

library(tidyverse)

df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
                  dose=rep(c("D0.5", "D1", "D2"),2),
                  len=c(6.8, 15, 33, 4.2, 10, 29.5))

myPalette <- c("#05eb92", "#119da4", "#ffc857")

myPalette_with_black <- setNames(c(myPalette, "black"), 
                                 c(as.character(seq_along(myPalette)), "-999"))

df2 <- df2 %>% 
  group_by(supp) %>% 
  mutate(dummy = ifelse(supp == "VC", as.character(row_number()), "-999"))

ggplot(data=df2, aes(x=dose, y=len, fill = dummy)) +
  geom_bar(stat="identity", position=position_dodge()) +
  scale_fill_manual(values = myPalette_with_black) +
  theme(legend.position = "none")

reprex package (v2.0.1)

于 2022 年 3 月 12 日创建