向包含其他行的ggplot2散点图添加图例 [英] Add a legend to a ggplot2 scatter plot including additional lines

查看:122
本文介绍了向包含其他行的ggplot2散点图添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在ggplot2散点图中添加图例,以区分回归线和我添加的单独线.

例如,

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)

此图上有两条线,一条红色回归线和一条黑色线,其方程式为y=x.

我设法在图例上添加了一条回归线,但想添加黑线.附带说明,我也很想能够从colour更改图例的名称.

解决方案

可能有一个更简单的解决方案,但这是到目前为止我能想到的最好的解决方案.

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)))

信用也位于此处.

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.

这篇关于向包含其他行的ggplot2散点图添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆