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

如何在R语言的ggpredict图形中标注p值与显著性?

解决ggpredict概率图添加显著性标记的报错问题

问题代码

library(ggeffects)
library(ggsignif)
library(ggplot2)

set.seed(42)

# 样本量
n <- 20

# 构建数据集
df <- data.frame(
  DV = sample(0:1, n, replace = TRUE),
  IV = sample(0:2, n, replace = TRUE)
)

# 拟合probit回归
reg <- glm(DV ~ IV, data = df, family=binomial(probit))

# 尝试绘制带显著性标记的预测图
graph <- ggpredict(reg, terms=c("IV")) %>% plot(ci = TRUE, colors = "bw", breaks=seq(0, 1, .25), limits=c(0, 1)) + 
  labs(title = NULL, y="", x="") +
  geom_signif(comparisons = list(c(0, 1)), map_signif_level = TRUE)

graph

报错信息

Error in `geom_signif()`:
! Problem while computing stat.
ℹ Error occurred in the 3rd layer.
Caused by error in `setup_params()`:
! Can only handle data with groups that are plotted on the x-axis
Run `rlang::last_trace()` to see where the error occurred.

解决方法

报错核心原因是ggpredict自带的plot()方法生成的ggplot对象中,x轴变量被当作连续型处理,而geom_signif需要x轴是离散的分组变量。我们可以手动提取预测数据,用ggplot重新构建图形,明确将x轴转为离散因子:

library(ggeffects)
library(ggsignif)
library(ggplot2)

set.seed(42)
n <- 20

df <- data.frame(
  DV = sample(0:1, n, replace = TRUE),
  IV = sample(0:2, n, replace = TRUE)
)

reg <- glm(DV ~ IV, data = df, family=binomial(probit))

# 提取预测数据
pred_data <- ggpredict(reg, terms=c("IV"))

# 手动构建ggplot图形
graph <- ggplot(pred_data, aes(x = as.factor(x), y = predicted)) +
  # 绘制预测点
  geom_point(size = 3) +
  # 绘制置信区间
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = 0.2) +
  # 设置y轴刻度和范围
  scale_y_continuous(breaks = seq(0, 1, .25), limits = c(0, 1)) +
  # 移除标题和轴标签
  labs(title = NULL, y = "", x = "") +
  # 使用黑白主题
  theme_bw() +
  # 添加显著性标记,分组值与x轴因子字符串对应
  geom_signif(comparisons = list(c("0", "1")), map_signif_level = TRUE)

graph

关键说明

  • 手动提取ggpredict结果后,将x轴变量x转换为因子,让geom_signif能识别离散分组。
  • geom_signif的comparisons参数中,分组值要和转换后的因子字符串保持一致(比如用"0"而非0)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:37:18