gpt4 book ai didi

r - 组内的ggplot scale_fill_manual

转载 作者:行者123 更新时间:2023-12-05 04:53:33 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com