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

在R语言中利用两个数据集创建数据框并绘制箱线图

合并数据集并绘制处理组Shannon多样性箱线图

步骤1:准备数据与计算Shannon指数

以下是生成群落矩阵、元数据及计算Shannon多样性指数的完整代码:

library(ggplot2)
library(vegan)
library(tidyverse)

# 创建群落矩阵(30个物种,20个群落)
set.seed(2)
community1 <- matrix(
  sample(0:250, 300, replace = TRUE), nrow = 10,
  dimnames = list(paste("community", 1:10, sep = ""), paste("sp", 1:30, sep = ""))
)
community2 <- matrix(
  sample(50:200, 300, replace = TRUE), nrow = 10,
  dimnames = list(paste("community", 11:20, sep = ""), paste("sp", 1:30, sep = ""))
)
community_matrix <- rbind(community1, community2)

# 创建处理组元数据表
m1 <- as.data.frame(list(paste("community", 1:10, sep = ""), rep("T1", 10)))
colnames(m1) <- c("Communities", "Treatment")
m2 <- as.data.frame(list(paste("community", 11:20, sep = ""), rep("T2", 10)))
colnames(m2) <- c("Communities", "Treatment")
metadata <- rbind(m1, m2)

# 计算Shannon多样性指数(先进行*稀疏化处理*)
raremax <- min(rowSums(community_matrix))
rarefied_data <- rrarefy(community_matrix, raremax)
H <- vegan::diversity(rarefied_data, index = "shannon")

步骤2:整合数据并绘制箱线图

合并数据集

将Shannon指数转换为带群落标识的数据框,再与元数据表按群落名匹配合并:

# 将Shannon指数转为数据框
shannon_df <- data.frame(
  Communities = names(H),
  Shannon = H
)

# 合并元数据与Shannon指数数据
combined_df <- merge(metadata, shannon_df, by = "Communities")

绘制自定义样式箱线图

使用ggplot2绘制不同处理组的Shannon多样性分布,可按需调整样式:

ggplot(combined_df, aes(x = Treatment, y = Shannon, fill = Treatment)) +
  geom_boxplot(width = 0.5, alpha = 0.7) + # 调整箱线图宽度与透明度
  geom_jitter(width = 0.1, color = "black", size = 1.5) + # 添加散点展示单个样本数据
  labs(
    title = "不同处理组的Shannon多样性指数分布",
    x = "处理组",
    y = "Shannon多样性指数"
  ) +
  theme_minimal() + # 使用简洁主题
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title = element_text(size = 12),
    legend.position = "none" # 因x轴已区分处理组,隐藏图例
  ) +
  scale_fill_brewer(palette = "Pastel1") # 自定义填充配色

关键说明

  • 稀疏化处理(rrarefy):消除不同群落样本量差异对多样性计算的干扰,统一将所有群落的物种丰度稀疏到最小样本量。
  • 数据合并:通过merge函数确保每个样本的处理组标签与对应的Shannon指数精准匹配。
  • 绘图优化:添加散点可直观展示单个样本的数值分布,自定义主题和配色提升图表可读性。

内容的提问来源于stack exchange,提问作者Angels Vásquez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:25:26