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

如何在R语言箱线图中添加Cohen's d值

给箱线图添加Cohen's d效应量标注

示例数据

d <- data.frame(
    Class= rep(c('First', 'Second'), 10),
    Response= rnorm(20,14,4)
)

原有代码

你原本的代码可绘制带抖动点的箱线图、添加t检验结果,同时单独计算Cohen's d:

library(ggpubr)
library(ggplot2)
library(effsize)
p <- ggboxplot(d, x = "Class", y = "Response",
               color = "Class", palette = "jco",
               add = "jitter")
p + stat_compare_means(method = "t.test")
with(d, cohen.d(Response,Class))

修改后代码(将Cohen's d添加到图中)

要把Cohen's d直接标注在箱线图上,可先计算效应量并格式化文本,再通过annotate()添加到图内:

library(ggpubr)
library(ggplot2)
library(effsize)

# 计算Cohen's d并格式化标注文本
cohen_res <- cohen.d(d$Response, d$Class)
cohen_label <- sprintf("Cohen's d = %.2f", cohen_res$estimate)

# 绘制箱线图,同时添加t检验结果和Cohen's d标注
p <- ggboxplot(d, x = "Class", y = "Response",
               color = "Class", palette = "jco",
               add = "jitter") +
  stat_compare_means(method = "t.test") +
  annotate(
    "text", 
    x = 1.5,  # 放在两个分类的中间位置
    y = max(d$Response) + 1,  # 放在响应变量最大值上方,避免遮挡数据
    label = cohen_label,
    size = 4
  )

# 输出图形
print(p)

说明

  • sprintf()用来格式化Cohen's d的数值,保留两位小数让标注更整洁
  • annotate()的x参数设为1.5,对应x轴两个分类(First对应1,Second对应2)的中间位置
  • y参数可根据你的数据范围调整,确保标注不会和箱线图或抖动点重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:18:30