【问题标题】:Plotting one predictor of a model that has several predictors with ggplot使用 ggplot 绘制具有多个预测变量的模型的一个预测变量
【发布时间】:2013-12-25 11:00:36
【问题描述】:

这是一个线性模型和一个ggplot的典型例子:

require(ggplot2)

utils::data(anorexia, package = "MASS")

anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                family = gaussian, data = anorexia)
coef(anorex.1)

   (Intercept)       Prewt   TreatCont     TreatFT 
     49.7711090  -0.5655388  -4.0970655   4.5630627 


ggplot(anorexia, aes(y=Postwt, x=Prewt)) + geom_point() + geom_smooth(method='lm', se=F)

我的问题是geom_smooth(...) 所做的回归与anorex.1 的模型不同,但是:

coef(lm(Postwt ~ Prewt, data=anorexia))

     (Intercept)       Prewt 
      42.7005802   0.5153804 

如何在 ggplot 上绘制模型 anorexia1

我可以只取 anorexia1 的截距 (49.77) 和估计 (-0.5655) 为 Prewt 并用 geom_abline(..) 绘制它,对吗?有没有更简单的解决方案?

【问题讨论】:

    标签: r plot ggplot2 lm


    【解决方案1】:

    由于您的模型包含两个预测变量(级别的不同截距值)和偏移变量,因此无法将其直接包含在 geom_smooth() 中。一种方法是为Treat 的所有三个级别创建包含Prewt 值的新数据框dat.new。然后使用这个新数据框使用您的模型预测所有级别的Postwt 值,并将预测值添加到新数据框

    new.dat<-data.frame(Treat=rep(levels(anorexia$Treat),each=100),
                        Prewt=rep(seq(70,95,length.out=100),times=3))
    anorexia.2<-data.frame(new.dat,Pred=predict(anorex.1,new.dat))
    head(anorexia.2)
      Treat    Prewt     Pred
    1   CBT 70.00000 80.18339
    2   CBT 70.25253 80.29310
    3   CBT 70.50505 80.40281
    4   CBT 70.75758 80.51253
    5   CBT 71.01010 80.62224
    6   CBT 71.26263 80.73195
    

    现在从原始数据框中绘制原始点,并使用包含预测的新数据框添加线。

    ggplot(anorexia,aes(x=Prewt,y=Postwt,color=Treat))+geom_point()+
      geom_line(data=anorexia.2,aes(x=Prewt,y=Pred,color=Treat))
    

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2021-01-21
      • 2017-12-07
      • 2018-01-04
      • 2015-04-23
      相关资源
      最近更新 更多