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

如何用phyloseq绘制分类阶元前20类的堆叠柱状图?

基于phyloseq绘制前20高丰度分类阶元的堆叠柱状图

通用实现思路

先针对指定分类阶元(门、属、种等)聚合类群,计算总丰度后筛选出前20个高丰度类群,剩余类群统一合并为「Others」,再用ggplot绘制堆叠柱状图。以下是可复用的代码方案:

通用函数代码

# 定义绘制前N个分类阶元堆叠柱状图的函数
plot_top_taxa_bar <- function(phyloseq_obj, rank = "Genus", top_n = 20, x_var = "Type") {
  # 按指定分类阶元聚合ITU
  taxa_aggregated <- tax_glom(phyloseq_obj, taxrank = rank)
  # 计算每个分类阶元的总丰度并排序
  total_abundance <- taxa_sums(taxa_aggregated)
  top_taxa_ids <- names(sort(total_abundance, decreasing = TRUE)[1:top_n])
  
  # 筛选前top_n个类群
  top_taxa_obj <- prune_taxa(top_taxa_ids, taxa_aggregated)
  # 合并剩余类群为"Others"
  remaining_taxa <- prune_taxa(setdiff(taxa_names(taxa_aggregated), top_taxa_ids), taxa_aggregated)
  remaining_taxa <- merge_taxa(remaining_taxa, taxa_names(remaining_taxa))
  tax_table(remaining_taxa)[, rank] <- "Others"
  
  # 合并前20类群与Others
  final_phyloseq_obj <- merge_phyloseq(top_taxa_obj, remaining_taxa)
  
  # 绘制堆叠柱状图
  p <- plot_bar(final_phyloseq_obj, fill = rank, x = x_var) +
    geom_bar(aes(color = !!sym(rank), fill = !!sym(rank)), stat = "identity", position = "stack") +
    labs(x = "", y = "Relative Abundance\n") +
    ggtitle(paste0("Top ", top_n, " ", rank, "s")) +
    theme_bw()
  return(p)
}

调用示例

绘制前20个属的堆叠柱状图

top20_genus_plot <- plot_top_taxa_bar(M.std_Species_filtered, rank = "Genus", top_n = 20)
print(top20_genus_plot)

绘制前20个门的堆叠柱状图

top20_phylum_plot <- plot_top_taxa_bar(M.std_Species_filtered, rank = "Phylum", top_n = 20)
print(top20_phylum_plot)

绘制前20个种的堆叠柱状图

top20_species_plot <- plot_top_taxa_bar(M.std_Species_filtered, rank = "Species", top_n = 20)
print(top20_species_plot)

代码说明

  • tax_glom():将ITU按指定分类阶元(如属、门)聚合
  • taxa_sums():计算每个分类阶元的总丰度,用于筛选高丰度类群
  • prune_taxa():保留目标类群,剔除其余类群
  • merge_taxa():将低丰度类群合并为「Others」,避免图例过于拥挤
  • !!sym(rank):动态引用分类阶元列名,让函数适配所有分类层级

内容的提问来源于stack exchange,提问作者M. Samir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:13:12