【发布时间】:2020-06-25 15:35:25
【问题描述】:
在 R 中使用以下 ggplot2 代码:
require(ggplot2)
df <- data.frame(x = rep(c(0, 1, 1.58,2, 2.58, 3, 3.32, 3.58, 4.17, 4.58, 5.58, 6.17, 6.5, 7.0),4), y = c(0.15,0.17,0.07,0.17,0.01,0.15,0.18,0.04,-0.06,-0.08,0,0.03,-0.27,-0.93,0.04,0.12,0.08,0.15,0.04,0.15,0.03,0.09,0.11,0.13,-0.11,-0.32,-0.7,-0.78,0.07,0.04,0.06,0.12,-0.15,0.05,-0.08,0.14,-0.02,-0.14,-0.24,-0.32,-0.78,-0.81,-0.04,-0.25,-0.09,0.02,-0.13,-0.2,-0.04,0,0.02,-0.05,-0.19,-0.37,-0.57,-0.81))
ggplot(df, aes(x = x, y = y)) + geom_point() +
stat_smooth(method = "lm", formula = y ~ x, size = 1, se = FALSE, aes(color = "black")) +
stat_smooth(method = "lm", formula = y ~ poly(x, 2), size = 1, se = FALSE, aes(color = "green")) +
stat_smooth(method = "lm", formula = y ~ poly(x, 3), size = 1, se = FALSE, aes(color = "orange")) +
stat_smooth(method = "gam", formula = y ~ s(x), size = 1, se = FALSE, aes(color = "blue")) +
theme(legend.justification=c(1,1),legend.position=c(0.45,0.45),legend.title=element_blank()) +
scale_color_manual(values=c("black","green","orange","blue"), labels=c("linear","quadratic","cubic","smooth"))
传说很好;但由于某种原因,四条曲线中的三条没有按预期着色:橙色曲线应为绿色,蓝色曲线应为橙色,绿色曲线应为蓝色。我错过了什么?
【问题讨论】:
-
为颜色传递一个命名向量以获得正确的顺序(如
values = c("black" = "black", ...)或尝试scale_color_identity()和guide = "legend"(因为身份比例默认为无指导)。我有一个例子这在一篇博文中here。