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

如何在Dunn.test后获取差异显著性字母并添加至ggplot箱线图?

从Dunn.test(Bonferroni校正)生成显著性字母并添加到ggplot箱线图

步骤1:加载所需包

先安装并加载必要工具包:

install.packages(c("dunn.test", "ggplot2", "multcompView"))
library(dunn.test)
library(ggplot2)
library(multcompView)

步骤2:处理Dunn.test结果生成显著性字母

假设你已经完成Dunn.test分析,结果结构如下(替换为你的实际结果):

# 示例Dunn.test输出结果
dunn_result <- structure(
  list(
    comparisons = structure(c(1L, 2L, 3L), .Label = c("A - B", "A - C", "B - C"), class = "factor"),
    Z = c(-1.234, -3.456, -2.222),
    P = c(0.217, 0.0005, 0.026)
  ),
  class = "data.frame",
  row.names = c(NA, -3L)
)

# 提取所有分组名称
groups <- unique(unlist(strsplit(as.character(dunn_result$comparisons), " - ")))

# 创建对称p值矩阵(multcompLetters要求的输入格式)
p_matrix <- matrix(1, 
                   nrow = length(groups), 
                   ncol = length(groups), 
                   dimnames = list(groups, groups))

# 填充两两比较的p值到矩阵
for (i in 1:nrow(dunn_result)) {
  comp_pair <- strsplit(as.character(dunn_result$comparisons[i]), " - ")[[1]]
  p_matrix[comp_pair[1], comp_pair[2]] <- dunn_result$P[i]
  p_matrix[comp_pair[2], comp_pair[1]] <- dunn_result$P[i]
}

# 生成显著性字母(基于Bonferroni校正后的p值,阈值设为0.05)
letter_groups <- multcompLetters(p_matrix, threshold = 0.05)$Letters

# 转换为数据框方便后续合并
letter_df <- data.frame(Group = names(letter_groups), Letters = as.character(letter_groups))

步骤3:准备绘图数据

假设你的原始数据包含Group(分组列)和Value(观测值列),先计算字母的放置位置(箱线图上方):

# 示例原始数据(替换为你的实际数据)
set.seed(123)
raw_data <- data.frame(
  Group = rep(c("A", "B", "C"), each = 20),
  Value = c(rnorm(20, 5, 1), rnorm(20, 5.5, 1), rnorm(20, 7, 1))
)

# 计算每个分组的字母放置位置(在箱线图最大值上方偏移0.3单位)
group_label_pos <- aggregate(Value ~ Group, data = raw_data, FUN = function(x) max(x) + 0.3)
# 合并字母数据与位置数据
group_label_data <- merge(group_label_pos, letter_df, by = "Group")

步骤4:绘制箱线图并添加显著性字母

全程不用管道,分步构建ggplot对象:

# 创建基础绘图对象
p <- ggplot(raw_data, aes(x = Group, y = Value))

# 添加箱线图元素
p <- p + geom_boxplot(fill = "#87CEEB", color = "black", width = 0.6)

# 添加显著性字母
p <- p + geom_text(data = group_label_data, 
                   aes(x = Group, y = Value, label = Letters), 
                   size = 5, 
                   fontface = "bold",
                   color = "darkred")

# 调整图表主题与标签
p <- p + theme_bw() + 
  labs(x = "分组", y = "测量值") +
  theme(axis.text = element_text(size = 12),
        axis.title = element_text(size = 14))

# 显示图表
print(p)

关键说明

  • multcompLetters会根据两两比较的p值,为无显著差异的组分配相同字母,有显著差异的组分配不同字母,符合学术常用的显著性标记规则。
  • 可调整group_label_pos中的+0.3来改变字母与箱线图的距离,适配你的数据范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:32:32