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

如何为geom_boxplot添加Dunn检验生成的紧凑字母标记(CLD)

解决geom_boxplot添加Dunn检验CLD字母的问题

核心问题修正

你之前的代码存在两个关键错误:

  1. 计算须线高度时错误引用全局df$result,导致所有组须线高度一致;
  2. 字母与须线数据合并逻辑错误,且geom_text的数据源和映射不匹配。

修正后完整代码

# 加载依赖包
library(ggplot2)
library(FSA)
library(multcompView)
library(dplyr)

# 生成模拟数据
df <- data.frame(
  Treatment = as.factor(rep(c('A', 'B', 'C', 'D'), each = 48)),
  result = rnorm(192, mean = c(0.8, 0.3, 0.65, 1), sd = c(0.02, 0.07, 0.9, 0.3))
)

# 执行Dunn事后检验
kw_test <- dunnTest(result ~ Treatment, data = df, method = "bonferroni", kw = TRUE)$res

# 生成紧凑字母显示(CLD)
kw_let <- cldList(P.adj ~ Comparison, data = kw_test, threshold = 0.05)
letters_df <- data.frame(Treatment = kw_let$Group, Letter = kw_let$Letter)

# 计算每组箱线图顶部须线高度(匹配ggplot箱线图逻辑)
top_whiskers <- df %>%
  group_by(Treatment) %>%
  summarise(
    top_whisker = {
      qs <- quantile(result, c(0.25, 0.75))
      iqr <- qs[2] - qs[1]
      max(result[result <= qs[2] + 1.5*iqr])
    }
  )

# 合并字母与须线数据,添加偏移量确保字母在须线上方
plot_labels <- merge(letters_df, top_whiskers, by = "Treatment")
plot_labels$label_y <- plot_labels$top_whisker + 0.1

# 绘制图形
p <- ggplot(df, aes(x = Treatment, y = result)) +
  geom_boxplot() +
  geom_jitter(alpha = 0.5) +
  geom_text(data = plot_labels, aes(x = Treatment, y = label_y, label = Letter),
            vjust = 0, size = 5) +
  coord_cartesian(ylim = c(-1, 3.2)) # 扩展y轴范围容纳字母

print(p)

关键调整说明

  • 须线高度计算:分组后使用组内result数据,严格匹配ggplot箱线图的须线生成逻辑(取组内不超过上四分位数+1.5*IQR的最大值);
  • CLD数据匹配:直接使用cldList输出的Group和Letter列,避免手动匹配出错;
  • 字母位置优化:在须线高度基础上添加固定偏移量,同时扩展y轴范围防止字母被截断;
  • 映射逻辑修正:使用合并后的plot_labels作为geom_text的数据源,确保x轴分组与字母、y轴位置完全对应。

内容的提问来源于stack exchange,提问作者A.Benson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:26:14