绘制ggplot2中没有交互作用的线性回归线 [英] plot linear regressions lines without interaction in ggplot2
本文介绍了绘制ggplot2中没有交互作用的线性回归线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码在ggplot2中绘制了交互回归线:
This code plots regression lines with interactions in ggplot2:
library(ggplot2)
ggplot(mtcars, aes(hp, mpg, group = cyl)) + geom_point() + stat_smooth(method = "lm")
交互被绘制成 stat_smooth
?
推荐答案
解决方法是将模型在 ggplot()
之外。然后对此模型进行预测并将结果添加到原始数据框中。这将添加列 fit ,
lwr
和 upr
。
Workaround would be to make model outside the ggplot()
. Then make predicition for this model and add result to the original data frame. This will add columns fit
, lwr
and upr
.
mod<-lm(mpg~factor(cyl)+hp,data=mtcars)
mtcars<-cbind(mtcars,predict(mod,interval="confidence"))
现在您可以使用 geom_line()
与 fit
值作为 y
添加三条回归线和 geom_ribbon()
加上 lwr
和 upr
来增加置信区间。
Now you can use geom_line()
with fit
values as y
to add three regression lines and geom_ribbon()
with lwr
and upr
to add confidence interval.
ggplot(mtcars, aes(hp, mpg, group = cyl)) + geom_point() +
geom_line(aes(y=fit))+geom_ribbon(aes(ymin=lwr,ymax=upr),alpha=0.4)
这篇关于绘制ggplot2中没有交互作用的线性回归线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文