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

无原始coxph对象时如何将Cox回归结果表转换为森林图

实现方案

该需求完全可以实现,无需原始coxph分析对象,仅需表格中已有的HR、95%置信区间、p值数据即可完成森林图绘制。

前置说明

你提供的GRP2示例数据存在列名重复问题,两个列均命名为HR.(univariable),实际应为单因素HR、多因素HR,以下代码会先修正该问题,再完成数据清洗与绘图。

第一步:加载依赖包

library(tidyverse)
library(forestplot)

第二步:数据清洗

核心工作是将HR字符串拆分为单独的HR点估计值、95%CI上下限、p值,同时补全变量名列的缺失值:

# 修正GRP2列名
colnames(GRP2)[4:5] <- c("HR.(univariable)", "HR.(multivariable)")

# 合并两组数据并清洗
clean_data <- bind_rows(GRP1 %>% mutate(group = "组1"), 
                        GRP2 %>% mutate(group = "组2")) %>%
  fill(Variable, .direction = "down") %>%
  # 拆分多因素HR列(如需画单因素可同理拆分对应列)
  separate(`HR.(multivariable)`, 
           into = c("hr", "ci", "p"), 
           sep = "( \\(|, p=)", 
           remove = FALSE,
           fill = "right") %>%
  mutate(ci = str_remove(ci, "\\)"),
         hr = as.numeric(hr)) %>%
  separate(ci, into = c("hr_low", "hr_high"), sep = "-", convert = TRUE) %>%
  mutate(p = str_remove(p, "\\)"),
         # 为参考组设置标识
         is_ref = is.na(hr),
         label = ifelse(is_ref, paste0(Level, "(参考)"), Level))

第三步:绘制森林图

以下为ggplot2绘制自定义森林图的示例,可根据需要调整样式匹配目标效果:

ggplot(clean_data, aes(x = hr, y = fct_rev(interaction(Variable, Level, lex.order = TRUE)))) +
  # 无效线
  geom_vline(xintercept = 1, linetype = "dashed", color = "gray50") +
  # 95%置信区间误差线
  geom_errorbarh(aes(xmin = hr_low, xmax = hr_high), height = 0.2, na.rm = TRUE) +
  # HR点估计值
  geom_point(aes(color = group), size = 3, na.rm = TRUE) +
  # HR数值标注
  geom_text(aes(label = `HR.(multivariable)`, x = 6), hjust = 0, na.rm = TRUE, size = 3) +
  # 按变量分面分组
  facet_grid(rows = vars(Variable), scales = "free_y", space = "free_y") +
  scale_x_log10(limits = c(0.2, 8)) +
  labs(x = "风险比 (HR, 95%CI)", y = "") +
  theme_bw() +
  theme(strip.text.y = element_text(angle = 0, hjust = 0),
        panel.grid.minor = element_blank())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:06:03