在ggplot2中绘制没有交互的线性回归线

时间:2014-05-18 14:19:40

标签: r ggplot2 regression

此代码用ggplot2中的交互绘制回归线:

library(ggplot2)
ggplot(mtcars, aes(hp, mpg, group = cyl)) + geom_point() + stat_smooth(method = "lm")

enter image description here

可以使用stat_smooth

绘制没有交互的行

1 个答案:

答案 0 :(得分:7)

解决方法是在ggplot()之外制作模型。然后对此模型进行预测并将结果添加到原始数据框。这将添加列fitlwrupr

mod<-lm(mpg~factor(cyl)+hp,data=mtcars)
mtcars<-cbind(mtcars,predict(mod,interval="confidence"))

现在,您可以使用geom_line() fity来添加三个回归线,geom_ribbon()添加lwrupr来添加置信区间。

ggplot(mtcars, aes(hp, mpg, group = cyl)) + geom_point() +
      geom_line(aes(y=fit))+geom_ribbon(aes(ymin=lwr,ymax=upr),alpha=0.4)

enter image description here