【问题标题】:In R ggplot2: How to assign colors in scale_fill_manual to a factor?在 R ggplot2 中:如何将 scale_fill_manual 中的颜色分配给一个因子?
【发布时间】:2020-10-07 08:10:38
【问题描述】:

我有一个样本数据集,我想在 ggplot 中绘制,用 scale_fill_manual 为变量组中的每个因子分配一个单独的颜色。但是,单个分配不能正常工作,因为您可以看到因子 a 和 b 没有得到不同的颜色。 这是我的代码和结果图。

#data
trt<-c("trt1","trt2","trt3","trt4","trt5","trt6","trt7")
emmean<-c(7.75,7.5,5.75,7,6,8,4)
group<-c("c","c","b","bc","b","c","a")

#specify color vector to get as many colors as group levels
library(RColorBrewer)
color_pallete_function <- colorRampPalette(
  colors = brewer.pal(8,"Dark2"),
  space = "Lab")

dat<-data.frame(trt,emmean,group)

dat$group<-as.factor(dat$group)
num_colors <- nlevels(dat$group)
diamond_color_colors <- color_pallete_function(num_colors)

#letter display plot
ggplot(data=dat, aes(x=reorder(trt,emmean),y=emmean,fill=group)) +
  geom_bar( stat="identity", width=0.8) +
  scale_fill_manual(values =diamond_color_colors[dat$group])+
  #geom_errorbar(aes(ymin=lower.CL, ymax=upper.CL), width=0.4) +
  geom_text(aes(y=8, label=group, angle=90)) +
  theme(legend.position = "none",
        axis.text.x = element_text(angle = 45,hjust=1)) + 
  annotate(geom="label", y=1, x=length(rownames(dat))-1, size=3, color="black", fill="white",
           label="Means with the same letter are according\n  to Tukey test (alpha=5%) not significantly different.")
 

如何解决?

【问题讨论】:

  • Error in color_pallete_function(num_colors) : could not find function "color_pallete_function"
  • 对不起,我刚刚添加了库 RColorBrewer

标签: r ggplot2


【解决方案1】:

要以稳健的方式将颜色分配给类别,请为您的颜色矢量命名,并在 scale_fill_manual 中使用此命名的颜色矢量。试试这个:

library(ggplot2)
library(RColorBrewer)

trt<-c("trt1","trt2","trt3","trt4","trt5","trt6","trt7")
emmean<-c(7.75,7.5,5.75,7,6,8,4)
group<-c("c","c","b","bc","b","c","a")

#specify color vector to get as many colors as group levels
color_pallete_function <- colorRampPalette(
  colors = brewer.pal(8,"Dark2"),
  space = "Lab")

dat<-data.frame(trt,emmean,group)

dat$group<-as.factor(dat$group)
num_colors <- nlevels(dat$group)
diamond_color_colors <- color_pallete_function(num_colors)
# Name your color vector
diamond_color_colors <-setNames(diamond_color_colors, levels(dat$group))

#letter display plot
ggplot(data=dat, aes(x=reorder(trt,emmean),y=emmean,fill=group)) +
  geom_bar( stat="identity", width=0.8) +
  scale_fill_manual(values = diamond_color_colors)+
  geom_text(aes(y=8, label=group, angle=90)) +
  theme(legend.position = "none",
        axis.text.x = element_text(angle = 45,hjust=1)) + 
  annotate(geom="label", y=1, x=length(rownames(dat))-1, size=3, color="black", fill="white",
           label="Means with the same letter are according\n  to Tukey test (alpha=5%) not significantly different.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多