Search code examples
rlegend-properties

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?


Solution

  • 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.