如何在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
相关产品推荐
相关产品推荐

