R语言篇pROC,ggroc绘制ROC曲线

主要目标:

1. 绘制ROC曲线

2. 计算ACU及置信区间

3. 找到最佳截断值


Code:

# 安装并加载包
library(pROC)
library(ggplot2)
# 创建模拟数据
set.seed(123) # 确保结果的可重复性
n <- 500 # 每组的样本数量
# 非糖尿病患者血糖水平(数据无实际意义)
non_diabetic_glucose <- rnorm(n, mean = 100, sd = 15)
# 糖尿病患者血糖水平(数据无实际意义)
diabetic_glucose <- rnorm(n, mean = 130, sd = 20)
# 创建血糖水平和标签
glucose_levels <- c(non_diabetic_glucose, diabetic_glucose)
diabetes_status <- c(rep(0, n), rep(1, n)) # 0代表非糖尿病,1代表糖尿病

# 创建ROC对象
roc_obj <- roc(diabetes_status, glucose_levels,smooth=F) # smooth可为T/F

# 绘制ROC曲线,计算AUC及其置信区间
plot(roc_obj,legacy.axes = TRUE,thresholds="best", # 基于约登指数选择roc曲线最佳阈值点
     print.thres="best")
auc_value <- auc(roc_obj) # 0.8786
auc_ci <- ci.auc(roc_obj) # 0.8575-0.8997 

# 用ggroc绘制
ggroc(roc_obj,legacy.axes = T,color="#B2533E",linewidth=0.8)+
  annotate(geom = "segment", x = 0, y = 0, xend =1, yend = 1,
           linetype="dashed",color="#186F65")+
  annotate("text",x=0.8,y=0.3,label="AUC = 0.879")+
  labs(x="1-Specificity",y="Sensitivity")+
  theme_bw()+
  theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank())


当smooth = T

roc_obj <- roc(diabetes_status, glucose_levels,smooth=T) # smooth可为T/F
auc_value <- auc(roc_obj)
# 用ggroc绘制
ggroc(roc_obj,legacy.axes = T,color="#B2533E",linewidth=0.8)+
  annotate(geom = "segment", x = 0, y = 0, xend =1, yend = 1,
           linetype="dashed",color="#186F65")+
  annotate("text",x=0.8,y=0.3,label="AUC = 0.879")+
  labs(x="1-Specificity",y="Sensitivity")+
  theme_bw()+
  theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank())