0

Im following this example Add regression line legend to geom_abline

Is there a reason the legend line is slanting? Is it possible for the legend to have a straight red and blue line?

stefan
  • 90,330
  • 6
  • 25
  • 51
L55
  • 117
  • 8

1 Answers1

2

Try this. You can choose the glyph for the legend with argument key_glyph. To get lines choose key_glyph = "path" in both geom_abline layers.

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, key_glyph = "path") + 
  geom_abline(aes(intercept = -1, slope = 0.5, colour = "line2"), lwd=1, key_glyph = "path") +
  scale_colour_manual(values=c("line1"="red","line2"="blue"))

Created on 2020-06-14 by the reprex package (v0.3.0)

stefan
  • 90,330
  • 6
  • 25
  • 51
  • I have modified the code to be the same as yours but its still on an angle rather than straight geom_abline(aes(colour="line3", intercept = -7.8, slope = 390, key_glyph = "path")) It says Ignoring unknown aesthetics: key_glyph – L55 Jun 14 '20 at 12:32
  • 1
    Don't put the `key_glyph = "path"` inside the `aes()`, .i.e. use `geom_abline(aes(colour="line3", intercept = -7.8, slope = 390), key_glyph = "path")`. (; – stefan Jun 14 '20 at 12:36