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

如何在R语言绘制的ROC曲线中添加截断标记点?

在R中绘制带截断值标记点的ROC曲线

要给ROC曲线添加截断值标记点,直接从pROC生成的roc对象中提取阈值、敏感性和特异性数据,结合ggplot2的geom_point就能快速实现,还可额外添加文本标注显示对应截断值。

修改后的完整代码

替换你原有的ggplot绘图部分,核心是先提取标记点数据,再添加到曲线中:

library(pROC)
library(randomForest)
library(ggplot2)

# 替换为你的真实数据
NfL <- c(...)  # 你的数值变量
Cstatus <- c(...)  # 0/1分类状态

plot(x=NfL, y=Cstatus)

glm.fit <- glm(Cstatus ~ NfL, family=binomial)
lines(NfL, glm.fit$fitted.values)

obj <- roc(Cstatus, glm.fit$fitted.values, ci=TRUE, plot=FALSE)
obj$ci

ciobj <- ci.se(obj, specificities=seq(0, 1, l=25))
dat.ci <- data.frame(x = as.numeric(rownames(ciobj)),
                     lower = ciobj[, 1],
                     upper = ciobj[, 3])

# 提取截断值对应的ROC曲线坐标数据
roc_points <- data.frame(
  x = 1 - obj$specificity,  # 匹配legacy.axes=TRUE的x轴(1-特异性)
  y = obj$sensitivity,
  threshold = obj$threshold
)

# 绘制带标记点的ROC曲线
ggroc(obj, legacy.axes=TRUE, linewidth=1) + 
  labs(x = "1 - Specificity \n AUC=0.9184 \n p=0.0022", y = "Sensitivity") + 
  theme_classic() + 
  geom_abline(slope=1, intercept = 0, linetype = "dashed", alpha=0.7) + 
  coord_equal() +
  geom_ribbon(data = dat.ci, aes(x = 1-x, ymin = lower, ymax = upper), fill = "steelblue", alpha=0.2) + 
  # 添加截断值标记点
  geom_point(data = roc_points, aes(x = x, y = y), color = "red", size = 2) +
  # 可选:添加截断值文本标注(调整hjust/vjust避免重叠)
  geom_text(data = roc_points, aes(x = x, y = y, label = round(threshold, 2)), 
            hjust = -0.2, vjust = 0, size = 3.5, color = "darkred") +
  ggtitle(capture.output(obj$ci)) + 
  theme(axis.text.x = element_text(color="black", size = 12), 
        axis.text.y = element_text(color="black", size=12),
        axis.title.x = element_text(face="bold", size=14), 
        axis.title.y = element_text(face="bold", size=14))

关键细节说明

  • roc_points数据框:从obj中直接提取specificity(特异性)、sensitivity(敏感性)、threshold(截断值)三个字段,将specificity转换为1-specificity以匹配legacy.axes=TRUE的x轴逻辑。
  • geom_point:用红色点标记每个截断值在ROC曲线上的位置,可通过color和size参数调整点的样式。
  • geom_text:可选功能,显示每个点对应的截断值,hjust和vjust参数用于调整文本相对于点的位置,避免与曲线或其他标签重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 10:02:28