在ggplot上添加回归线 [英] Adding a regression line on a ggplot

查看:769
本文介绍了在ggplot上添加回归线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我努力在ggplot上添加回归线。我第一次尝试使用abline,但我没有设法使其工作。然后我试了这个... ...

pre $ data $ data = data.frame(x.plot = rep(seq(1,5), 10),y.plot = rnorm(50))
ggplot(data,aes(x.plot,y.plot))+ stat_summary(fun.data = mean_cl_normal)+
geom_smooth(method =' lm',formula = data $ y.plot〜data $ x.plot)

但它不是一般来说,为了提供你自己的公式,你应该使用参数 x c $ c>和 y ,它们将对应您在 ggplot()中提供的值 - 在这种情况下 x 将被解释为 x.plot y y.plot 。有关平滑方法和公式的更多信息,可以在函数 stat_smooth()的帮助页面中找到,因为它是由 geom_smooth()
pre $ ggplot = mean_cl_normal)+
geom_smooth(method ='lm',formula = y〜x)

如果您使用的是您在 ggplot()调用中提供的相同x和y值,并且需要绘制线性回归线,则不需要使用公式在 geom_smooth()中,只需提供 method =lm

  ggplot(data,aes(x.plot,y.plot))+ stat_summary(fun.data = mean_cl_normal)+ 
geom_smooth(method ='lm' )


I'm trying hard to add a regression line on a ggplot. I first tried with abline but I didn't manage to make it work. Then I tried this...

data = data.frame(x.plot=rep(seq(1,5),10),y.plot=rnorm(50))
ggplot(data,aes(x.plot,y.plot))+stat_summary(fun.data=mean_cl_normal) +
   geom_smooth(method='lm',formula=data$y.plot~data$x.plot)

But it is not working either.

解决方案

In general, to provide your own formula you should use arguments x and y that will correspond to values you provided in ggplot() - in this case x will be interpreted as x.plot and y as y.plot. More information about smoothing methods and formula you can find in help page of function stat_smooth() as it is default stat used by geom_smooth().

ggplot(data,aes(x.plot,y.plot))+stat_summary(fun.data=mean_cl_normal) + 
  geom_smooth(method='lm',formula=y~x)

If you are using the same x and y values that you supplied in the ggplot() call and need to plot linear regression line then you don't need to use the formula inside geom_smooth(), just supply the method="lm".

ggplot(data,aes(x.plot,y.plot))+stat_summary(fun.data=mean_cl_normal) + 
  geom_smooth(method='lm')

这篇关于在ggplot上添加回归线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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