Here is an typical example of linear model and a 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)
My problem is that the regression that is made by geom_smooth(...)
is not the same model than anorex.1
but is:
coef(lm(Postwt ~ Prewt, data=anorexia))
(Intercept) Prewt
42.7005802 0.5153804
How can I plot the model anorexia1
on a ggplot?
Could I just take the intercept (49.77) and estimate (-0.5655) of anorexia1
for Prewt
and plot it with geom_abline(..), is it correct? Is there a simpler solution?
As you have model that contains two predictors (different intercept values for levels) and also offset variable it won't e possible to directly include it in geom_smooth()
. One way would be to make new data frame dat.new
that contains values of Prewt
for all three levels of Treat
. Then use this new data frame to predict Postwt
values for all levels using your model and add predicted values to new data frame
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
Now plot original points from the original data frame and add lines using new data frame that contains predictions.
ggplot(anorexia,aes(x=Prewt,y=Postwt,color=Treat))+geom_point()+
geom_line(data=anorexia.2,aes(x=Prewt,y=Pred,color=Treat))
来源:https://stackoverflow.com/questions/20451927/plotting-one-predictor-of-a-model-that-has-several-predictors-with-ggplot