尝试根据字符串更改 ggplot geom_bar 中一个变量的颜色

Trying to change colour of one variable in ggplot geom_bar dependent on the string

我有一个 for 循环 运行 通过一吨微生物组数据(使用 phyloseq)并为多个实验生成图表。

  ggplot(data_M1, aes(x = Sample, y = Abundance, fill = get(i))) +
    geom_bar(stat = "identity")+
    facet_wrap(vars(Status, Time.Point, Treatment), scales = "free", ncol=2)+
    theme(axis.title.x=element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank())+
    guides(fill = guide_legend(reverse = TRUE, keywidth = 1, keyheight = 1, title = i))+
    ylab(yaxisname)+
    ggtitle(plotname)+
  ggsave(ggsavename, last_plot())

示例结果:

不过我想做的是将所有“_unclassified”样本/测序数据设为灰色...所以也许我需要某种带有 str_contains 的 if 语句?

如果需要,很高兴提供一个可重现的示例,但有人可能有一个简单的解决方案。

谢谢!

@camille 关于最小 可重现示例的评论是 germaine。我们不需要了解您的 facetguide 或致电 ggsave 来回答您的问题。

首先,生成一些测试数据

library(tidyverse)

d <- tibble(
       Species=rep(c("s__reuteri", "s__guilliermondii", 
                     "o__Clostridiales_unclassified", "k__bacteria_unclassified"), 
                   each=4),
       Sample=as.factor(rep(1:4, times=4)),
       Abundance=runif(16)
     )

生成自定义标签和颜色

labels <- unique(d$Species)
# Make sure length of availableColours is long enough to accommodate the maximum length of labels
availableColours <- c("red", "blue", "green", "orange", "yellow")
legendColours <- ifelse(str_detect(labels, fixed("unclassified")), "grey", availableColours)

创建剧情

d %>% 
  ggplot(aes(x=Sample, y=Abundance, fill=Species)) +
  geom_bar(stat="identity") +
  scale_fill_manual(labels=labels, values=legendColours)

给予

如果要“汇集”所有未分类的物种,那么

d1 <- d %>% 
        mutate(
          LegendSpecies=ifelse(
                          str_detect(
                            Species, 
                            fixed("unclassified")
                          ), 
                          "Unclassified", 
                          Species
                        )
        )

legendColours <- ifelse(str_detect(unique(d1$LegendSpecies), fixed("Unclassified")), "grey", availableColours)

d1 %>% 
  ggplot(aes(x=Sample, y=Abundance, fill=LegendSpecies)) +
  geom_bar(stat="identity")+
  scale_fill_manual(labels=unique(d1$LegendSpecies), values=legendColours)

给予