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

使用ggpubr给ggplot箱线图加显著性标记时找不到y.position如何解决

报错原因

stat_pvalue_manual() 函数的输入统计检验表必须包含 y.position 字段,用于指定每个显著性标注在图上的Y轴放置位置,你调用compare_means()生成的默认检验结果中没有该字段,因此触发找不到变量的报错。

解决方法

使用ggpubr自带的add_y_position()函数自动为检验结果生成合适的Y轴位置参数即可,也可手动根据你的绘图数据范围自定义y.position取值。

修正后可运行的完整代码

library(reshape)
library(ggplot2)
library(ggpubr)

regcovMat <- read.table("Test.txt", sep="\t", header=T)
molten.data <- melt(regcovMat)
stat.test <- compare_means(
  value ~ variable, data = molten.data,
  method = "t.test"
)
# 自动生成y.position,step.increase参数控制不同组对标注的高度间隔
stat.test <- add_y_position(stat.test, step.increase = 0.02)

p <- ggplot(molten.data, aes(x=variable, y=value, fill=variable)) + 
  geom_boxplot() +
  theme_cowplot() +
  theme(legend.position = "top")
p + stat_pvalue_manual(stat.test, label = "p")
可选优化设置
  • 若要显示显著性星号而非原始p值,将stat_pvalue_manual的label参数改为"p.signif"
  • 若要隐藏显著性标注的上下连线尖端,可增加参数tip.length = 0
  • 若需要手动指定标注高度,可直接给stat.test新增y.position列:stat.test$y.position <- c(0.12, 0.14, 0.16...),数值根据你的数据Y轴范围自行调整

内容的提问来源于stack exchange,提问作者Shrilaxmi M S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:09:03