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
相关产品推荐
相关产品推荐

