Add a legend to a ggplot2 scatter plot including a

2019-02-28 01:47发布

问题:

I would like to add a legend to a ggplot2 scatter graph which distinguishes between a regression line and a separate line I've added.

For example,

library(ggplot2)
set.seed(123)
data1=rnorm(1000,1,2)
data2=rnorm(1000,1,4)
DF=data.frame(data1,data2)

ggplot(DF,aes(data1,data2))+geom_point(colour="dodgerblue",alpha=0.75)+geom_smooth(method=lm,se=F,aes(colour="Line of best fit"))+
  geom_abline(intercept = 0, slope = 1, linetype="dashed", colour="black", alpha=1,size=1)

There are two lines on this plot, a red regression line, and a black line with equation y=x.

I have managed to add a regression line to the legend, but would like to add the black line. As a side note, I'd also love to be able to change the name of the legend from colour.

回答1:

There is probably a simpler solution, but here's the best I could come up with so far.

ggplot(DF, aes(data1,data2)) + 
  geom_point(colour="dodgerblue",alpha=0.75) +
  geom_abline(aes(colour="abline", intercept=0, slope=1), linetype="dashed", alpha=1, size=1) +
  geom_smooth(aes(colour="lm_smooth"), method = "lm", se=FALSE) + 
  scale_colour_manual(name="lines", values=c("red", "blue")) + 
  guides(colour = guide_legend(override.aes = list(alpha = 0)))

Credit also goes here.