You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R绘制微生物组相对丰度y轴占比异常及筛选top类群问题咨询

问题解决方法

1. Y轴总丰度不符合100%规则的问题

原因

你当前Y轴总丰度超过100%的核心原因是x轴映射的是分组变量GroupDay,而非单个样本ID:geom_col()默认会将同一GroupDay下所有样本的丰度值累加后堆叠,若一个分组下有n个样本,总高度就会是n*100%,也就会出现你看到的150%、80%这类不符合预期的数值。

解决方案

根据你的分析需求二选一即可:

  • 方案1:展示每个样本的相对丰度
    将x轴映射改为样本ID,可配合facet_wrap()按GroupDay分面展示,此时每个柱对应单个样本,总高度为100%。
    代码示例:
    ggplot(data = psmelt(ps_oral_ra), mapping = aes(x= Sample, y= Abundance, color= Phylum, fill= Phylum )) + 
      geom_col() +  
      labs(x = "", y = "Relative Abundance\n") +
      facet_wrap(~GroupDay, scales = "free_x") +
      theme_classic() +
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
    
  • 方案2:展示每个GroupDay的组内平均相对丰度
    绘图前先按分组和分类水平计算平均丰度,再绘制堆叠柱图,此时每个分组的柱总高度为100%。
    代码示例(门水平):
    library(dplyr)
    ps_melt <- psmelt(ps_oral_ra)
    # 按分组和门计算平均丰度
    phylum_mean <- ps_melt %>%
      group_by(GroupDay, Phylum) %>%
      summarise(mean_abundance = mean(Abundance), .groups = "drop")
    # 绘图
    ggplot(phylum_mean, aes(x = GroupDay, y = mean_abundance, fill = Phylum, color = Phylum)) +
      geom_col() +
      labs(x = "", y = "Relative Abundance\n") +
      theme_classic()
    

2. 筛选Top10/Top20属水平类群绘图的方法

优先先将物种注释聚合到属水平,再按总丰度筛选排名靠前的类群,可选择将剩余类群合并为「Other」避免图例过于杂乱,代码示例如下:

library(phyloseq)
library(dplyr)
# 1. 将物种注释聚合到属水平
ps_genus <- tax_glom(ps_oral, taxrank = "Genus", NArm = FALSE)
# 2. 计算所有属的总丰度,取Top20(要Top10则将20改为10即可)
genus_total_abun <- taxa_sums(ps_genus)
top20_genus <- names(sort(genus_total_abun, decreasing = TRUE)[1:20])
# 3. 可选操作:将非Top20的属统一命名为Other
tax_table(ps_genus)[!rownames(tax_table(ps_genus)) %in% top20_genus, "Genus"] <- "Other"
# 4. 重新按属聚合、计算相对丰度
ps_genus_merge <- tax_glom(ps_genus, taxrank = "Genus")
ps_genus_ra <- transform_sample_counts(ps_genus_merge, function(x){x/sum(x)})
# 后续按前述绘图逻辑绘制属水平堆叠柱图即可

内容的提问来源于stack exchange,提问作者Mashael Aljumaah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 20:06:06