r - 组内的ggplot scale_fill_manual

标签 r ggplot2 bar-chart visualization

我正在尝试使用 scale_fill_manual 更改我的 ggplot 中各个条形的颜色,但我遇到了麻烦,因为这些条形 组(此处为“条件”)。我该如何克服这个问题?

这是我的数据集:

df <- data.frame(
"condition" = c("A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B"), 
"type" = c("Apple", "Apple", "Apple", "Apple", "Pear", "Pear", "Pear", "Pear", "Orange", "Orange", "Orange", "Orange", "Tomato", "Tomato", "Tomato", "Tomato", "Tomato", "Berry", "Berry", "Berry"), 
"ripeness" = c("bad","bad", "good", "good", "bad", "bad", "good", "good", "bad","bad", "good", "good", "bad", "bad", "good", "good", "bad","bad", "good", "good"), 
count = c(19, 4, 7, 2, 7, 7, 1, 13, 16, 16, 31, 13, 30, 12, 39, 17, 1, 36, 4, 27)
)

以及我用来绘制它的代码:

plot <- ggplot(df, aes(x=type, y=count, fill=ripeness)) +
  geom_bar(stat="summary", width = .7, position = position_dodge(width = .75)) +
  theme_light()

#the below is non-working code
plot + scale_fill_manual(values=c("black","blue","black","green","black","stripes-2","black","stripes-3","black", "yellow"))

如何指定各个条形的颜色?出于解释的目的,我写了颜色名称,但会将它们换成 html 颜色代码。后来,我还打算使用 ggpattern ( https://coolbutuseless.github.io/package/ggpattern/articles/geom-gallery-geometry.html#colour-example-1 ) 对我的两个条形图进行纹理处理,但如果太难的话,这不需要在这篇文章中解决。

我正在尝试在 r 中重新创建此图:

enter image description here

最佳答案

一种方法是在数据框中添加一列颜色并使用 scale_fill_identity

library(dplyr)
library(ggplot2)

colors <- c("black","blue","black","green","black","orange",
            "black","pink","black", "yellow")

df %>%
  distinct(type, ripeness) %>%
  mutate(color = colors) %>%
  inner_join(df, by = c('type', 'ripeness')) %>%
  ggplot(aes(x=type, y=count, fill=color)) +
  geom_bar(stat="summary", width = .7, position = position_dodge(width = .75)) +
  theme_light() +
  scale_fill_identity()

enter image description here

PS - 我无法使 “stripes-2”“stripes-3” 颜色正常工作,所以将其更改为其他随机颜色。

关于r - 组内的ggplot scale_fill_manual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65988418/

相关文章:

R:当字符串超过设置长度时,在 grid.table 中换行文本

r - 创建 ggplot2 函数并根据 ggplot2 标准功能将参数指定为数据中的变量

python - matplotlib 中的图例问题

r - 如何在同一页面中打印多个绘图(ggplot)

重新访问变量 X 的无效类型(列表),其中 X 是日期类

r - 如何将一列数据框保留为数据框

r - 在 ggplot 中使用 geom_vline() 复制图例

gnuplot - Gnuplot:如何用彩色背景和图案填充条形图

R - 仅按第一个空格分割数据框

r - 如何在 Likert 图的每个条形上输出正确的百分比?