简体   繁体   中英

plot linear regressions lines without interaction in 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")

在此输入图像描述

Can lines without interactions be plotted with stat_smooth ?

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"))

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)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM