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

如何优化R语言亚组分析森林图,使方块大小匹配样本量与置信区间宽度

要实现森林图中方块大小与置信区间宽度负相关(CI越窄方块越大)的效果,可以通过以下两种方案实现:

方案1:自定义ggplot2绘制(灵活度最高)

直接提取Cox模型的效应量、置信区间结果,手动映射方块大小:

library(dplyr)
library(ggplot2)
library(survival)
library(broom)

# 数据处理与模型拟合(与你原有逻辑一致)
pretty_lung <- lung %>%
  transmute(time,
            status,
            Age = age,
            Sex = factor(sex, labels = c("Male", "Female")),
            ECOG = factor(lung$ph.ecog),
            `Meal Cal` = meal.cal)
cox_fit <- coxph(Surv(time, status) ~ ., pretty_lung)

# 提取模型结果,计算用于映射大小的指标
cox_res <- tidy(cox_fit, exponentiate = TRUE, conf.int = TRUE) %>%
  mutate(
    # CI越窄,该值越大,对应方块越大
    point_size = 5/(conf.high - conf.low) 
    # 系数5可根据需要调整,想要更大方块就调大,反之调小
  )

# 绘制森林图
ggplot(cox_res, aes(x = estimate, y = term)) +
  geom_errorbarh(aes(xmin = conf.low, xmax = conf.high), height = 0.2) +
  geom_point(aes(size = point_size), shape = 15, color = "black") + # shape=15是方块
  geom_vline(xintercept = 1, linetype = "dashed", color = "gray60") +
  scale_x_log10() + # HR默认用对数坐标轴更合理
  labs(x = "风险比 (HR, 95%CI)", y = "变量") +
  theme_bw() +
  theme(legend.position = "none") # 隐藏大小图例

方案2:修改forestmodel输出结果

如果需要保留forestmodel默认的森林图排版,可直接修改其返回的ggplot对象的方块大小参数:

library(forestmodel)
# 原有绘图逻辑,先把图存在变量p里
p <- forest_model(coxph(Surv(time, status) ~ ., pretty_lung))
# 替换方块大小映射,系数3可根据视觉效果调整
p$layers[[2]]$aes_params$size <- 3/(cox_res$conf.high - cox_res$conf.low)
print(p)

如果是多水平分类变量的亚组分析,提取结果时注意每个亚组的CI宽度要和对应变量顺序匹配即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:57:03