如何在R中使用ggplot2绘制具有loess和spline回归的协变量?

3

我知道如何使用只有一个独立变量的loess和spline回归进行绘图。

library(tidyverse)

# loess
ggplot(mtcars, aes(x = mpg, y = drat)) + 
  geom_point() + 
  geom_smooth(method = 'loess', formula = y ~ x)

# splines
ggplot(mtcars, aes(x = mpg, y = drat)) + 
  geom_point() + 
  geom_smooth(method = 'lm', formula = y ~ splines::bs(x, 8))

引起我的注意的是,我有多个独立变量,例如x1x2x3,我创建了一个模型,如下所示:y ~ x1 + x2 + x3,我只想用loess或spline绘制yx1之间的曲线。

我尝试了但失败了。

cylgear是模型中的协变量,我只对dratmpg感兴趣。


# loess
ggplot(mtcars, aes(x = mpg, y = drat)) + 
  geom_point() + 
  geom_smooth(method = 'loess', formula = y ~ x + cyl + gear)
# splines
ggplot(mtcars, aes(x = mpg, y = drat)) + 
  geom_point() + 
  geom_smooth(method = 'lm', formula = y ~ splines::bs(x, 8)+ cyl + gear)

非常感谢您的帮助。

1个回答

1

一种方法是分别拟合loess并绘制带置信区间的拟合线。

fit = predict(loess(drat ~ mpg + cyl + gear, data=mtcars, span=0.5), se=T)
#tem = predict(loess(drat~ mpg,data=mtcars), se=T)

dat = mtcars
dat$loess = fit$fit
dat$ymax  = fit$fit + fit$se.fit * abs(qnorm((1-0.95)/2))
dat$ymin  = fit$fit - fit$se.fit * abs(qnorm((1-0.95)/2))

ggplot(dat, aes(x = mpg, y = drat)) + 
  geom_point() + 
  geom_line(aes(y=loess), color='blue', size=1) +
  geom_ribbon(aes(ymin=ymin, ymax=ymax), alpha=0.2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接