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

如何用R的interactions包给逻辑回归分类交互图添加OR、95%CI及交互P值?

在R的interactions包分类交互图中添加OR值、95%CI及交互项P值

你需要在interactions::cat_plot生成的逻辑回归交互图上添加OR值、95%置信区间(CI)标签,以及交互项的P值,可按以下步骤实现:

完整代码实现

library(interactions)
library(ggplot2)
library(dplyr)
library(broom) # 用于提取模型参数

# 生成模拟数据
set.seed(154)
outcome=sample(c(0,1), 1000, replace=TRUE)
set.seed(158)
factor1=sample(c("A","B"), 1000, replace=TRUE)
set.seed(1258)
factor2=sample(c("D","F"), 1000, replace=TRUE)

df <- data.frame(outcome, factor1, factor2)
df$outcome <- as.factor(df$outcome)

# 拟合带交互项的逻辑回归模型
fit3 <- glm(outcome ~ factor1*factor2, data = df, family=binomial(link="logit"))

# 1. 提取OR值、95%CI并整理标签
model_params <- tidy(fit3, conf.int = TRUE) %>%
  mutate(
    OR = exp(estimate),
    OR_low = exp(conf.low),
    OR_high = exp(conf.high),
    # 生成OR(95%CI)的文本标签
    or_label = sprintf("OR=%.2f\n(95%%CI: %.2f-%.2f)", OR, OR_low, OR_high),
    # 匹配factor1和factor2的分组
    factor1 = case_when(
      term == "(Intercept)" ~ "A",
      term == "factor1B" ~ "B",
      term == "factor2F" ~ "A",
      term == "factor1B:factor2F" ~ "B"
    ),
    factor2 = case_when(
      term == "(Intercept)" ~ "D",
      term == "factor1B" ~ "D",
      term == "factor2F" ~ "F",
      term == "factor1B:factor2F" ~ "F"
    )
  ) %>%
  # 只保留四个分组的参数
  filter(!is.na(factor1))

# 2. 提取交互项的P值
interaction_p <- model_params %>%
  filter(term == "factor1B:factor2F") %>%
  pull(p.value) %>%
  sprintf("交互项P值: %.4f", .)

# 3. 生成交互图并添加标签
cat_plot(fit3, pred = factor1, modx = factor2, interval = TRUE) +
  # 添加OR和CI标签,位置调整到点的上方
  geom_text(
    data = model_params,
    aes(x = factor1, y = plogis(estimate) + 0.05, label = or_label, color = factor2),
    size = 3,
    show.legend = FALSE
  ) +
  # 添加交互项P值到图的右上角
  annotate(
    "text",
    x = Inf, y = Inf,
    label = interaction_p,
    hjust = 1.1, vjust = 1.1,
    size = 4
  )

关键步骤说明

  • 提取模型参数:用broom::tidy()提取模型的系数、置信区间,通过exp()转换为OR值,再生成格式化的标签文本,同时匹配每个标签对应的factor1和factor2水平。
  • 获取交互项P值:从参数表中筛选出交互项(factor1B:factor2F)的P值,格式化为可读文本。
  • 添加标签到图中:
    • 用geom_text()将OR和CI标签添加到每个数据点的上方,通过y = plogis(estimate) + 0.05调整位置避免与点重叠;
    • 用annotate()将交互项P值放置在图的右上角,通过hjust和vjust调整位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:55:27