Add legend for abline to ggplot geom_point

Viewed 255

I would like to add a legend, that only describes the lines in my plot, which is similar to this one:

library(ggplot)

df<-as.data.frame(cbind(seq(1:10), seq(from=2, to=20, 2)))
ggplot(data=df, aes(V1, V2))+geom_point()+
  geom_abline(intercept=0, slope=1)

I only want to add the abline to the legend. I already tried to work with geom_line, but it vanishes when I adjust the x and ylims of the plot. ggplot2 does not have the option to build a legend from scratch similar to lattice, does it?enter image description here

2 Answers

You can wrap the geom_abline parameters in an aes() and add a color element, which is then controlled in the scale_color_manual() call:

   ggplot(data=df, aes(V1, V2)) +
      geom_point() +
      geom_abline(aes(color="whatever", intercept=0, slope=1)) +
      scale_color_manual(values = "red") +
      labs(color=NULL)

enter image description here

Or you can do it for both different colours:

ggplot(data = df, aes(color="red", V1, V2)) + geom_point() + 
  geom_abline(aes(intercept = 0, slope = 1, color="blue")) + 
  scale_color_manual(values = c("red", "blue")) +
  labs(color=NULL)

enter image description here

Related