如何在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
相关产品推荐
相关产品推荐

