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

如何在RStudio中为每个样本单独设置堆叠条形图分段排序

微生物相对丰度堆叠条形图实现方案

核心步骤:数据预处理 + 绘图

1. 加载依赖包

library(tidyverse)

2. 数据导入与格式转换

假设你的数据集为宽格式(行=物种,列=样本),文件名为microbiota_data.csv:

# 读取数据并转成长格式
data <- read.csv("microbiota_data.csv", row.names = 1) %>%
  rownames_to_column("Species") %>%
  pivot_longer(cols = -Species, names_to = "Sample", values_to = "Abundance")

3. 样本内排序与Others分组

设定低丰度阈值(示例为1%),将低于阈值的物种合并为Others,并按丰度排序:

# 自定义低丰度阈值(可根据需求调整)
low_abundance_threshold <- 0.01

processed_data <- data %>%
  group_by(Sample) %>%
  # 计算相对丰度(若数据已是相对丰度,可删除此行)
  mutate(Relative_Abundance = Abundance / sum(Abundance)) %>%
  # 标记是否归为Others
  mutate(Group = ifelse(Relative_Abundance >= low_abundance_threshold, Species, "Others")) %>%
  # 按丰度降序排序,确保Others排在最后
  arrange(Sample, desc(Relative_Abundance), Group) %>%
  # 生成专属因子水平,固定每个样本内的排序
  mutate(Group = factor(Group, levels = unique(Group))) %>%
  ungroup()

4. 绘制堆叠条形图

ggplot(processed_data, aes(x = Sample, y = Relative_Abundance, fill = Group)) +
  geom_bar(stat = "identity", position = "stack") +
  # 反转填充顺序,让Others显示在条形顶部
  scale_fill_discrete(limits = rev(levels(processed_data$Group))) +
  labs(title = "样本微生物物种相对丰度分布", x = "样本编号", y = "相对丰度") +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

注意事项

  • 若你的原始数据已是相对丰度,直接删除代码中计算Relative_Abundance的行即可。
  • 可根据数据分布调整low_abundance_threshold的值,比如改为0.02(2%)来筛选低丰度物种。
  • 若样本名称显示拥挤,可调整axis.text.x中的angle参数(比如改为60)优化显示。

内容的提问来源于stack exchange,提问作者Sam lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 09:22:08