【问题标题】:How to add covariates in loess and spline regression and then plot it in r with ggplot2如何在黄土和样条回归中添加协变量,然后使用 ggplot2 在 r 中绘制它
【发布时间】:2020-10-02 07:03:35
【问题描述】:

我知道如何用一个自变量绘制黄土和样条回归。

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,我只想用黄土或样条曲线绘制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)

我们将不胜感激。

【问题讨论】:

    标签: r ggplot2 model regression


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2016-04-06
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多