R语言如何绘制时间依赖ROC曲线

什么是时间依赖ROC曲线

时间依赖ROC(Time-dependent ROC)是一种扩展了经典ROC曲线的方法,专门用于生存分析中评估预测模型在不同时间点的表现。传统的ROC曲线主要用于二分类问题,评估模型在单一时刻的分类能力,而时间依赖ROC曲线则考虑了生存数据中的时间因素。

  • 在生存分析中,数据不仅包括事件的发生(如死亡、疾病的发生等),还包括事件发生的时间。时间依赖ROC曲线则结合了“时间”这一因素,在多个不同时间点上评估模型的预测能力。

  • 例如,在疾病预测模型中,时间依赖ROC曲线可以告诉我们在第1年、第3年和第5年时,模型对于预测是否会发生某个事件(如死亡)的能力。

绘图前的数据准备

demo数据可以在这里下载

https://www.r2omics.cn/res/demodata/timeROC.txt

输入数据包括3列,第1列是生存时间(这里是年),第2列是状态(0表示Alive,1表示Dead),第3列是风险得分(或者其他)

R语言如何绘制时间依赖ROC曲线

# 代码来源:https://www.r2omics.cn/
# 加载所需的库 ------------------------------------------------------------
library(tidyverse)
library(survival)
library(timeROC)
library(ggstyle) # 开发版安装方式devtools::install_github("sz-zyp/ggstyle")

# 读取数据 --------------------------------------------------------------------
dfKM = read.delim("https://www.r2omics.cn/res/demodata/timeROC.txt")


# 进行时间依赖性ROC分析 ------------------------------------------------------
years = c(1, 3, 5) # 设置需要计算AUC的预测时间点,1年、3年、5年
ROC2 = timeROC(
  T = dfKM$Time,   # 生存时间
  delta = as.numeric(dfKM$Status),# 结局状态(生死,转化为数值型)
  marker = dfKM$RiskScore,        # 风险评分(作为预测变量)
  cause = 1,       # 阳性结局赋值为1
  weighting = "marginal",   # 权重计算方法,"marginal"表示采用Kaplan-Meier估计删失分布
  times = years,   # 指定预测的时间点:1年、3年、5年
  iid = F          # 设置为F,因为只有使用"marginal"时才能计算置信区间
)

# 整理结果并绘图 --------------------------------------------------------
# 整理数据
dfAUC = ROC2$AUC %>%
  data.frame() %>%
  set_names("AUC") %>%
  rownames_to_column("Group") %>%
  mutate(Group = str_remove(Group, "t=")) %>%
  tibble()

dfPlot = bind_cols(
  ROC2$TP %>% data.frame(check.names = F) %>% set_names(paste0("TP_", years)),
  ROC2$FP %>% data.frame(check.names = F) %>% set_names(paste0("FP_", years))
) %>%
  mutate(row_number = row_number()) %>%
  pivot_longer(-row_number, names_to = "Sample", values_to = "Value") %>%
  separate(Sample, into = c("Type", "Group"), sep = "_") %>%
  pivot_wider(names_from = Type, values_from = Value) %>%
  left_join(dfAUC) %>%
  mutate(Label = paste0(Group, " year AUC=", round(AUC, 3)))  # 创建AUC标签,显示为"1 year AUC=0.85"

# 绘图
ggplot(dfPlot, aes(x = FP, y = TP,
                   group = factor(Label, levels = unique(Label)),
                   color = factor(Label, levels = unique(Label)))) +
  geom_line(size=1) +
  geom_segment(aes(x = 0, y = 0, xend = 1, yend = 1),
               colour = 'grey',
               linetype = 'dotdash'
  ) +
  labs(x = "1-Specificity", y = "Sensitivity", color = "") +
  ggstyle::scale_color_sci(palette = "Set1",modeColor = "1")+ # 设置颜色
  ggstyle::theme_style1()+ # 设置主题
  theme(
    legend.position = c(0.95, 0.05),  # 设置图例位置在右下角
    legend.justification = c(1, 0)    # 设置图例对齐方式为右下角
  )+
    coord_fixed(ratio = 1)  # 设置坐标轴比例为1:1,确保X轴和Y轴比例一致