简体   繁体   中英

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?

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

在此处输入图片说明

With slight modification your code works just fine:

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

Added legend position in case if you want to change that aswell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM