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

ggplot绘制ROC曲线时scale_x_reverse报错问题求助

解决ROC曲线绘制中x轴反转的冲突问题

出现这个警告是因为ggroc()函数已经默认生成了x轴的比例尺,手动添加scale_x_reverse()相当于重复定义x轴比例尺,因此触发提示。要实现x轴从0到1的顺序,有两种更合适的方法:

方法1:直接使用ggroc的内置参数

ggroc本身提供了reverse参数,专门用来控制x轴的方向,这是最简洁的方案:

library(titanic)
library(pROC)
library(ggplot2)
r <- roc(Survived ~ Fare, data = titanic_train)

# AUC文本计算
auc <- auc(r)
ci <- ci.auc(r)
ci_l <- round(ci[1], 2)
ci_u <- round(ci[3], 2)

legend_text <- paste0("AUC = ", round(auc, 2), " (95% CI = ", ci_l, " - ", ci_u, ")")

# 绘制ROC曲线,直接设置reverse=TRUE
p <- ggroc(r, reverse = TRUE) +
  labs(
    title="ROC",
    y = "Sensitivity",
    x = "1 - Specificity"
  ) +
  geom_segment(aes(x=0, xend=1, y=0, yend=1), color="grey", linetype="dashed") +
  annotate("text", x = 0.7, y = 0.05, label = legend_text)

print(p)

注意:设置reverse=TRUE后,对角线的坐标要从x=1, xend=0改成x=0, xend=1,才能正确显示参考线;同时标注文本的x坐标也需要调整(比如从0.3改成0.7),确保在反转后的轴上位置合理。

方法2:修改现有x轴比例尺的方向

如果需要手动调整比例尺,可以用scale_x_continuous()替代scale_x_reverse(),通过trans参数反转轴方向,避免重复定义:

p <- ggroc(r) +
  scale_x_continuous(trans = "reverse", limits = c(1, 0)) +
  labs(
    title="ROC",
    y = "Sensitivity",
    x = "1 - Specificity"
  ) +
  geom_segment(aes(x=1, xend=0, y=0, yend=1), color="grey", linetype="dashed") +
  annotate("text", x = 0.3, y = 0.05, label = legend_text)

print(p)

这种方法会覆盖默认的x轴比例尺,但不会触发重复定义的警告,同时保留原有的对角线和标注位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:13:36