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

如何为多模型ROC曲线的图例配置对应颜色?

解决ROC曲线图例与曲线颜色不匹配问题

问题出在你手动覆盖图例颜色时,没有和model因子的实际顺序精准对应,同时额外添加的文本注释也没必要。以下是修复后的完整方案:

修复思路

  1. 直接将带AUC值的标签作为model列的取值,让ggplot自动关联标签与曲线
  2. 使用scale_color_manual通过名称映射指定颜色,彻底避免顺序不匹配问题
  3. 移除冗余的文本注释,直接通过图例展示AUC信息

修复后代码

# 计算AUC并构造带标签的模型名称
model_labels <- c(
  paste('Model 1 (AUC=', round(auc(roc_model1), 3), ')'),
  paste('Model 2 (AUC=', round(auc(roc_model2), 3), ')'),
  paste('Model 3 (AUC=', round(auc(roc_model3), 3), ')'),
  paste('Model 4 (AUC=', round(auc(roc_model4), 3), ')')
)

# 构造数据框时直接使用带AUC的标签作为model值
data <- rbind(
  data.frame(fpr = roc_model1$specificities, tpr = roc_model1$sensitivities, model = model_labels[1]),
  data.frame(fpr = roc_model2$specificities, tpr = roc_model2$sensitivities, model = model_labels[2]),
  data.frame(fpr = roc_model3$specificities, tpr = roc_model3$sensitivities, model = model_labels[3]),
  data.frame(fpr = roc_model4$specificities, tpr = roc_model4$sensitivities, model = model_labels[4])
)

# 绘制ROC曲线
ggplot(data, aes(x = 1 - fpr, y = tpr, color = model)) +
  geom_line(size = 0.8) +
  labs(x = "False Positive Rate", y = "True Positive Rate") +
  geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
  theme_minimal() +
  theme(legend.position = "bottomright") +
  # 通过名称精准映射每个模型的颜色
  scale_color_manual(values = c(
    model_labels[1] = "blue",
    model_labels[2] = "red",
    model_labels[3] = "green",
    model_labels[4] = "purple"
  )) +
  guides(color = guide_legend(title = NULL, label.position = "bottom", label.hjust = 1))

关键说明

  • 用名称映射颜色的方式,无论model列的顺序如何,颜色都会和对应标签精准匹配
  • 直接将AUC嵌入模型标签,既简化了代码,又让图例信息更直观
  • 移除了annotate的文本注释,避免了信息重复和视觉混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:48:35