我对此进行了编码:
ggplot() +
geom_point(mapping = aes(x = X, y = y)) +
geom_abline(intercept = -0.9930872, slope = 0.4866284, colour = "red") +
geom_abline(intercept = -1, slope = 0.5, colour = "blue")
但似乎无法获得我的最小二乘和回归线的工作传奇。我尝试了各种堆栈溢出答案,但似乎没有什么能给我我需要的东西。
Add a legend to a ggplot2 scatter plot including additional lines
这看起来是最好的答案,但我无法让它发挥作用!
有什么建议吗?
答案 0 :(得分:2)
set.seed(1234)
X <- rnorm(20,sd=2.5)
y <- -1+0.5*X+rnorm(20, sd=0.4)
library(ggplot2)
ggplot() +
geom_point(mapping = aes(x = X, y = y)) +
geom_abline(aes(intercept = -0.9930872, slope = 0.4866284, colour = "line1"), lwd=1) +
geom_abline(aes(intercept = -1, slope = 0.5, colour = "line2"), lwd=1) +
scale_colour_manual(values=c("line1"="red","line2"="blue"))
答案 1 :(得分:0)
稍作修改,您的代码就可以正常运行:
ggplot() +
geom_point(mapping = aes(x = X, y = y)) +
geom_abline(aes(colour = "line_1", intercept = -0.9930872, slope = 0.4866284)) +
geom_abline(aes(colour = "line_2", intercept = -1, slope = 0.5)) +
scale_colour_manual(name = "lines", values = c("red", "blue")) +
theme(legend.position = "bottom")
添加图例位置,以防您想要更改它。