在 ggplot 上添加回归线 [英] Adding a regression line on a 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)
但它也不起作用.
推荐答案
一般来说,要提供您自己的公式,您应该使用参数 x
和 y
这将对应于您在 ggplot()
中提供的值 - 在这种情况下 x
将被解释为 x.plot
和 y
y.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屋!