BioF3 FigCode · SCI 绘图代码集

Cox 森林图(Forest Plot (Cox))

导出日期:2026年6月27日

分类:生存分析 | 依赖包:survival、survminer

解决的生物学问题

在校正其他临床变量后,我的 risk score / 基因仍然是独立预后因子吗?

应用场景

输入数据格式

coxph 对象(包含多个协变量)

关键参数

快速开始

1. 直接在线运行

打开 FigCode 在线绘图,点击本工具卡片的"在线绘图"按钮即可用内置示例数据出图,零环境配置。

2. 本地复现

下载脚本和示例数据,本地 RStudio 运行:

# 下载
curl -O https://<your-site>/figcode/scripts/forest-cox.R
curl -O https://<your-site>/figcode/data/forest-cox.csv

3. 安装依赖

# CRAN 包
install.packages(c("survival", "survminer"))

# Bioconductor 包(如需)
# BiocManager::install(c())

完整代码

library(survival)
library(survminer)

# --- Demo data ---
set.seed(42)
n <- 300
df <- data.frame(
  time     = rexp(n, 0.04),
  status   = sample(0:1, n, replace = TRUE, prob = c(0.3, 0.7)),
  risk_score = rnorm(n),
  age      = sample(40:80, n, replace = TRUE),
  stage    = factor(sample(c("I","II","III","IV"), n, replace = TRUE)),
  gender   = factor(sample(c("Female","Male"), n, replace = TRUE))
)

# --- Multivariate Cox ---
fit <- coxph(Surv(time, status) ~ risk_score + age + stage + gender, data = df)

# --- Forest plot ---
ggforest(
  fit, data = df,
  main = "Multivariate Cox — Hazard Ratios",
  cpositions = c(0.02, 0.22, 0.4),
  fontsize = 0.9,
  refLabel = "ref",
  noDigits = 2
)

替换为自己的数据

脚本中以 # --- Demo data --- 标注的段落是示例数据生成代码。替换为自己的数据时,保持列名一致即可:

延伸阅读