0

我有一个 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语句?

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

谢谢!

4

1 回答 1

0

@camille 关于最小可重现示例的评论是germaine。facet我们不需要对您的 s、guides 或来电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)

给予

在此处输入图像描述

于 2022-01-07T16:16:56.900 回答