简体   繁体   中英

Add a legend to a ggplot2 scatter plot including additional lines

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 .

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 .

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