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

如何在R Studio中绘制包含3组的Kaplan-Meier生存曲线?

解决Kaplan-Meier生存曲线合并绘制问题

核心思路

不需要拆分数据集,先创建一个新的分组变量,把原始数据中的Group和Response组合成你需要的三组,再用survival和survminer包一次性绘制所有曲线。

步骤与代码

  1. 安装并加载必备包
    如果你还没安装survival(拟合KM模型)和survminer(绘制美观的生存曲线),先执行安装命令:

    install.packages(c("survival", "survminer"))
    

    加载包:

    library(survival)
    library(survminer)
    
  2. 创建新分组变量
    基于原始数据的Group和Response列,生成包含三组的新变量new_group,两种方法任选一种:

    • Base R 写法:
      # 假设你的数据集名为df
      df$new_group <- ifelse(df$Group == "normal", "Normal",
                             ifelse(df$Group == "high" & df$Response == "responder", "High Responder",
                                    "High Non-responder"))
      
    • dplyr 写法(适合用tidyverse的用户):
      library(dplyr)
      df <- df %>%
        mutate(new_group = case_when(
          Group == "normal" ~ "Normal",
          Group == "high" & Response == "responder" ~ "High Responder",
          Group == "high" & Response == "non-responder" ~ "High Non-responder"
        ))
      
  3. 拟合Kaplan-Meier模型
    用Surv()函数定义生存对象,再用survfit()拟合三组的KM曲线:

    km_fit <- survfit(Surv(Days, Outcome) ~ new_group, data = df)
    

    注意:确保Outcome是数值型变量(0=截尾,1=事件),如果是字符型,用as.numeric(df$Outcome)转换。

  4. 绘制合并曲线
    用ggsurvplot()生成包含三组的生存曲线,可自定义样式:

    ggsurvplot(km_fit,
               data = df,
               conf.int = TRUE,          # 显示置信区间
               palette = c("#E7B800", "#2E9FDF", "#FC4E07"), # 自定义每组颜色
               legend.title = "Groups",
               legend.labs = c("Normal", "High Responder", "High Non-responder"), # 图例标签
               xlab = "Days",            # X轴标题
               ylab = "Survival Probability", # Y轴标题
               surv.median.line = "hv")  # 显示中位生存时间的水平线和垂直线
    

额外提示

  • 若想调整曲线样式(如线条粗细、图例位置),可在ggsurvplot()中添加参数(比如linetype = "strata"设置不同线型,legend = "bottom"把图例放底部)。
  • 可以用summary(km_fit)查看每组的生存时间统计信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:41:33