2017-10-15 69 views
-2

我编写这样的:添加回归线传奇geom_abline

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") 

,但似乎无法得到一个工作传说为我的最小二乘populuation回归线。我试过各种堆栈溢出的答案,但似乎没有给我我需要的东西。

Add a legend to a ggplot2 scatter plot including additional lines

这看起来像最好的答案,但我不能得到它的工作!

有什么建议吗?

回答

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") 

增加了传奇地位。

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")) 

enter image description here

+0

这看起来很完美!我明天会试试...谢谢! – PS94