物种组成相对丰度(百分比)堆叠柱状图

该博客介绍了如何对百分比堆叠柱状图的X轴、柱状图内部和图例进行排序,并展示了如何根据丰度筛选数据。首先,通过读取和合并多个数据集,然后计算每个属的总数并排序。接着,按降序排列属以确定图例顺序,并计算样本中属的比例以决定X轴排序。最后,通过ggplot2绘制图表,并在需要时仅展示丰度最高的10个属。整个过程详细阐述了数据预处理和可视化的方法。

百分比堆叠柱状图有三个地方是可以进行排序处理的:
1,X轴上的样本顺序
2,柱状图内部方块的顺序
3,图例的顺序

分三步:

一, 数据读取与预处理

#分步读入数据
anabaena <- read.table("anabaena.txt", stringsAsFactors = FALSE, header = TRUE)
filter <- read.table("filter.txt", stringsAsFactors = FALSE, header = TRUE)
polysiphonia <- read.table("polysiphonia.txt", stringsAsFactors = FALSE, header = TRUE)
sediment <- read.table("sediment.txt", stringsAsFactors = FALSE, header = TRUE)

#合并数据
for(i in list(filter, polysiphonia, sediment)){
  anabaena <- anabaena %>% full_join(i,  by = c("anabaena" = colnames(i)[1]))
}

#更改列名并处理缺失值
sumall <- anabaena
colnames(sumall) <- c("genus", "anabaena", "filter", "polysiphonia", "sediment")
sumall[is.na(sumall)] <- 0

二,各要素排序处理

#添加一列,计算每个属的数量和
sumall$sum <- rowSums(sumall[ , 2:ncol(sumall)])

#按升序排序genus因子水平,用于柱状图内部排序
order1 <- sort(sumall$sum, index.return = TRUE, decreasing = FALSE )
sumall$genus <- factor(sumall$genus, levels = sumall$genus[order1$ix])

#按降序记录genus顺序,用于图例排序
sumall <- arrange(sumall, desc(sum))
genus_order <- as.vector(sumall$genus)

#删除添加的sum列
sumall <- sumall[ , -6] 

#计算最多的属在各样本中的比例,以降序排列样本位置,用于X轴样本排序
Per <- (as.matrix(sumall[1, 2:ncol(sumall)])) / t(as.matrix(colSums(sumall[ , 2:ncol(sumall)])))
order2 <- sort(as.numeric(Per), index.return = TRUE, decreasing = TRUE)
sumall <- sumall[ ,c(1, order2$ix+1)]

#宽数据转长数据
sumalls <- melt(sumall, id.vars = "genus")

三,作图

ggplot(data = sumalls,aes(variable, value, fill = genus))+ 
  geom_bar(stat = "identity", position = "fill", color = "SlateGrey", width = 0.8, size = 0.25)+
  ylab("Relative Abundance") +
  scale_fill_discrete(limits = genus_order) +
  theme(
    axis.title.x = element_blank(), 
    axis.title = element_text(size = 15, face = "plain", color = "black"),
    axis.text = element_text(size = 12, face = "plain", color = "black"),
    legend.title = element_text(size = 14, face = "plain", color = "black"),
    legend.position = "right"
  )

在这里插入图片描述
四,如果只想展示丰度最高的10个属
在第二步处理前进行如下处理:

#降序排列各属
sumall <- arrange(sumall, desc(sum))
#取丰度前10的部分
sumall1 <- sumall[c(1:10), ]
#其余部分折叠为others
others <- colSums(sumall[11:nrow(sumall) , 2:ncol(sumall)])
others <- as.data.frame(t(others))
others$genus <- "others"
#合并前10部分与其余others部分
sumall <- rbind(sumall1, others)

作图:

ggplot(data = sumalls,aes(variable, value, fill = genus))+ 
  geom_bar(stat = "identity", position = "fill", color = "SlateGrey", width = 0.8, size = 0.25)+
  ylab("Relative Abundance") +
  scale_fill_manual(values=brewer.pal(11,"Set3"),limits = genus_order) +
  theme(
    axis.title.x = element_blank(), 
    axis.title = element_text(size = 15, face = "plain", color = "black"),
    axis.text = element_text(size = 12, face = "plain", color = "black"),
    legend.title = element_text(size = 14, face = "plain", color = "black"),
    legend.position = "right"
  )

在这里插入图片描述

### 如何用 Python 或 R 绘制物种组成堆叠柱状图 #### 使用 Python 绘制堆叠柱状图 以下是基于 Python 的解决方案,利用 `pandas` 和 `matplotlib` 库来实现物种组成数据的堆叠柱状图。 首先,准备数据并将其转换为适合绘的形式: ```python import pandas as pd import matplotlib.pyplot as plt import numpy as np # 假设这是输入的数据框 (样本 vs 物种相对丰度) data = { 'Sample': ['S1', 'S2', 'S3'], 'Species_A': [40, 30, 50], 'Species_B': [20, 30, 10], 'Species_C': [40, 40, 40] } df = pd.DataFrame(data) # 将 Sample 列设置为索引 df.set_index('Sample', inplace=True) # 转置 DataFrame 方便绘 df_transposed = df.T ``` 接着,使用 `matplotlib` 来绘制堆叠柱状图: ```python fig, ax = plt.subplots(figsize=(8, 6)) # 设置颜色列表 colors = ['#ff9999','#66b3ff','#99ff99'] # 绘制堆叠条形 df_transposed.plot(kind='bar', stacked=True, color=colors, ax=ax) # 添加标签和其他细节 ax.set_title('Stacked Bar Chart of Species Composition') ax.set_xlabel('Samples') ax.set_ylabel('Relative Abundance (%)') # 显示例 plt.legend(title="Species", bbox_to_anchor=(1.05, 1), loc='upper left') # 展示形 plt.tight_layout() plt.show() ``` 上述代码实现了基本的堆叠柱状图功能,并通过自定义颜色增强了可视化效果[^1]。 --- #### 使用 R 绘制堆叠柱状图 在 R 中可以借助 `ggplot2` 包完成类似的表制作。以下是具体方法: 首先安装必要的包(如果尚未安装),然后加载它们: ```r install.packages("ggplot2") # 如果未安装 ggplot2,则运行此命令 library(ggplot2) ``` 创建一个简单的数据集作为例子: ```r # 创建数据框 data <- data.frame( Sample = c("S1", "S1", "S1", "S2", "S2", "S2", "S3", "S3", "S3"), Species = rep(c("A", "B", "C"), times = 3), RelativeAbundance = c(40, 20, 40, 30, 30, 40, 50, 10, 40) ) ``` 接下来,调用 `ggplot()` 函数构建堆叠柱状图: ```r # 构建堆叠柱状图 ggplot(data, aes(x = Sample, y = RelativeAbundance, fill = Species)) + geom_bar(stat = "identity", position = "stack") + scale_fill_manual(values = c("#ff9999","#66b3ff","#99ff99")) + # 自定义配色方案 labs(title = "Stacked Bar Chart of Species Composition", x = "Samples", y = "Relative Abundance (%)", fill = "Species") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) ``` 这段脚本会生成一张清晰直观的堆叠柱状图,其中不同颜色代表不同的物种及其对应的相对丰度[^3]。 --- #### 总结 无论是采用 Python 还是 R 编程语言,都可以高效地完成物种组成数据的堆叠柱状图绘制工作。Python 更加灵活易学,而 R 提供了强大的统计分析工具以及高度定制化的作能力。两者各有千秋,可根据个人偏好和技术背景选择合适的工具。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值