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

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

问题描述

我正在努力在 ggplot 上添加回归线.我第一次尝试使用 abline,但我没能成功.然后我尝试了这个...

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)

但它也不起作用.

推荐答案

一般来说,要提供您自己的公式,您应该使用参数 xy 这将对应于您在 ggplot() 中提供的值 - 在这种情况下 x 将被解释为 x.plotyy.plot.您可以通过函数 stat_smooth() 的帮助页面找到有关平滑方法和公式的更多信息,因为它是 geom_smooth() 使用的默认统计数据.

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. You can find more information about smoothing methods and formula via the help page of function stat_smooth() as it is the 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)

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

If you are using the same x and y values that you supplied in the ggplot() call and need to plot the 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天全站免登陆