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

如何在R语言forestploter森林图同一行绘制多水平置信区间?

解决forestploter同一行展示多水平置信区间的问题

问题说明

需在同一行用不同颜色/样式绘制90%与95%置信区间,复刻《Regression Modeling Strategies: With Applications to Linear Models, Logistic Regression, and Survival Analysis (2015)》第468页的图19.10。原代码通过forest()传入多组置信区间列表会生成多行条目,无法实现同一行叠加效果。

解决方案

利用forestploter的add_ci()函数,先绘制基础的95%置信区间森林图,再叠加绘制90%置信区间,通过设置不同颜色、线宽区分两个区间。

修改后的完整代码

library(survival)
library(forestploter)
library(data.table)

# 拟合Cox比例风险模型
reg <- coxph(Surv(time, status) ~ age + sex + ph.ecog + ph.karno, data = lung)

# 提取模型参数并计算HR、置信区间、P值等
variables <- names(coef(reg))
beta <- coef(reg)
se <- sqrt(diag(reg$var))
HR <- exp(beta)
p <- 1 - pchisq((beta / se)^2, 1)
CI_95 <- exp(confint(reg))
CI_90 <- exp(confint(reg, level = 0.90))
CI_hr_95 <- sprintf("%.2f (%.2f to %.2f)", HR, CI_95[, 1], CI_95[, 2])

# 构建结果数据表
essai <- data.table(
  variables,
  beta,
  p = round(p, 3),
  HR,
  CI_95_lower = CI_95[, 1],
  CI_95_upper = CI_95[, 2],
  CI_90_lower = CI_90[, 1],
  CI_90_upper = CI_90[, 2],
  CI_hr_95
)
essai$` ` <- paste(rep(" ", 50), collapse = " ")

# 定义森林图主题:区分两个CI的样式与图例
tm <- forest_theme(
  base_size = 12,
  ci_pch = 10,
  # 95% CI用黑色粗线,90% CI用灰色细线
  ci_col = c("black", "gray50"),
  ci_lwd = c(3, 1.5),
  legend_name = "置信区间",
  legend_value = c("95%", "90%"),
  legend_position = "top"
)

# 先绘制95%置信区间的基础森林图
forest_data <- essai[, c(1, 9, 10, 3)]
forest <- forest(
  forest_data,
  est = essai$HR,
  lower = essai$CI_95_lower,
  upper = essai$CI_95_upper,
  sizes = 0.5,
  ci_column = 3,
  ref_line = 1,
  ticks_at = c(0, 1, 5.3),
  xlim = c(0, 5.3),
  theme = tm,
  arrow_lab = c("更长生存期", "更短生存期")
)

# 叠加绘制90%置信区间
forest <- add_ci(
  forest,
  est = essai$HR,
  lower = essai$CI_90_lower,
  upper = essai$CI_90_upper,
  ci_col = "gray50",
  ci_lwd = 1.5,
  ci_pch = NA  # 复用基础图的点标记,无需额外添加
)

# 生成最终森林图
plot(forest)

关键修改说明

  • 放弃多列表传入forest():原代码中est = list(...)会生成多行条目,改用"基础图+叠加"的方式实现同一行展示。
  • 用add_ci()叠加区间:该函数可在已生成的森林图对象上添加新的置信区间,实现同一行的多层展示。
  • 区分CI视觉样式:通过ci_col和ci_lwd设置不同区间的颜色、线宽,配合图例明确区分,匹配目标图的样式要求。
  • 优化图例配置:调整主题图例的内容与位置,确保样式与实际绘制的CI对应,提升图的可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:40:22