2013-12-08 53 views
1

这里的模型的一个预测值是线性模型的一个典型的例子和ggplot:绘制具有几个预测与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

我可以对Prewt采取anorexia1的截距(49.77)和估计值(-0.5655),并用geom_abline(..)作图,是否正确?有一个更简单的解决方案吗?

回答

3

当你有一个包含两个预测(对于不同水平截距值),也offset变量不会Ë可能模式可以直接将其包含在geom_smooth()。一种方法是使一个包含Prewt值全部三个级别的Treat新的数据帧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)) 

enter image description here