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

ggplot2绘图无法添加图例,scale_color_manual()执行无效果怎么解决?

错误原因

ggplot2 的图例仅会基于 aes() 内部定义的美学映射自动生成,你当前代码中将 color 参数写在 geom_line 的 aes() 外部,属于手动硬编码颜色,没有绑定映射变量,因此不会触发生成图例,后续的 scale_color_manual 也不会生效。

解决方案

方案1(推荐,符合 ggplot2 设计逻辑):宽表转长表后统一映射

先将数据集转为长格式,再统一配置映射规则:

library(tidyr)
# 宽表转长表
averages_long <- pivot_longer(averages, 
                              cols = c(P_pred, P_true),
                              names_to = "类别", 
                              values_to = "概率值")
# 绘图代码
ggplot(data = averages_long, aes(x = as.integer(Deciles))) +
  scale_x_reverse(breaks = 10:1) +
  geom_line(aes(y = 概率值, color = 类别), size = 2) + 
  labs(x = "Deciles", y = "Probabilities", color = "指标类型") +
  scale_color_manual(values = c("P_pred" = "darkred", "P_true" = "darkgreen"))

方案2(无需修改原数据集):在 aes 内定义颜色映射标签

如果不想改动原数据集,直接将颜色标签放到 aes() 内部即可触发生成图例:

ggplot(data = averages, aes(x = as.integer(Deciles))) +
  scale_x_reverse(breaks = 10:1) +
  geom_line(aes(y = P_pred, color = "P_pred"), size = 2) + 
  geom_line(aes(y = P_true, color = "P_true"), size = 2) +
  labs(x = "Deciles", y = "Probabilities", color = "指标类型") +
  scale_color_manual(values = c("P_pred" = "darkred", "P_true" = "darkgreen"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:06