gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:53:24 25 4
gpt4 key购买 nike

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

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

enter image description here

可以用 stat_smooth 绘制没有相互作用的线吗? ?

最佳答案

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

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

现在您可以使用 geom_line()fit值为 y添加三个回归线和 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

关于r - 在ggplot2中绘制没有交互的线性回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com