Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

r - Add regression line legend to geom_abline

I've coded this:

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

but cannot seem to get a working legend for my least square and populuation regression line. I've tried various stack overflow answers but nothing seems to give me what I need.

Add a legend to a ggplot2 scatter plot including additional lines

This looked like the best answer, but I can't get it to work!

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...