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

ggplot2绘制观测值与拟合值时拟合值图例不显示如何解决

问题原因

你代码中geom_line的color参数写在了aes()映射规则之外,属于硬编码的固定样式,没有被纳入ggplot的颜色映射体系,因此scale_color_identity无法识别到绿色对应的映射值,自然不会生成拟合值的图例条目。

优化后代码(最小改动版本)

仅需把geom_line的color参数移入aes()内即可:

library(ggplot2)
data(iris)
fit = lm(Petal.Width ~ Petal.Length, data=iris)
fit = predict(fit)

ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = "red")) +
  geom_point() +
  # 将color参数移入aes中,纳入映射体系
  geom_line(aes(y = fit, color = "green"), size = 1) +
  scale_color_identity(name = "图例",
                       breaks = c("red", "green"),
                       labels = c("观测值", "拟合值"),
                       guide = "legend")

更规范的推荐写法

直接将颜色映射关联分类标签,无需使用identity scale,可读性更强也更容易维护:

library(ggplot2)
data(iris)
fit = lm(Petal.Width ~ Petal.Length, data=iris)
# 建议将拟合值存入原数据集,避免向量长度不匹配的潜在问题
iris$fitted <- predict(fit)

ggplot(iris, aes(x = Petal.Length)) +
  geom_point(aes(y = Petal.Width, color = "观测值")) +
  geom_line(aes(y = fitted, color = "拟合值"), size = 1) +
  scale_color_manual(name = "图例",
                     values = c("观测值" = "red", "拟合值" = "green"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:06:07