Linear Regression Plots in R

A linear regression prediction plot may help you display the predictions of your regression along with the corresponding uncertainty.

mod1<-lm(Response~Explanatory1, data=mydata)
summary(mod1)

graphdata1<-expand.grid(Explanatory1=c(XXX)) #Put in interesting values of Explanatory1

graphdata1<-cbind(graphdata1, predict(mod1, graphdata1, se=TRUE))

graphdata1<-cbind(graphdata1, LL=graphdata1$fit-1.96*graphdata1$se.fit, UL=graphdata1$fit+1.96*graphdata1$se.fit)

#Plot these predictions with their uncertainties
ggplot(data=graphdata1)+
geom_line(aes(x=Explanatory1, y=fit), color=”red”, size=2)+
geom_errorbar(aes(x=Explanatory1, y=fit, ymin=LL, ymax=UL),width=0.1, size=2)+
geom_point(aes(x=Explanatory1, y=fit), color=”black”, size=3)

## Now suppose we have two possible explanatory variables

mod2<-lm(Response~Explanatory1+Explanatory2, data=mydata)
summary(mod2)

graphdata2<-expand.grid(Explanatory1=c(XXX), Explanatory2=c(XXX))

#Put in interesting values of Explanatory1 and Explanatory2

graphdata2<-cbind(graphdata2, predict(mod2, graphdata2, se=TRUE))

graphdata2<-cbind(graphdata2,
LL=graphdata2$fit-1.96*graphdata2$se.fit,
UL=graphdata2$fit+1.96*graphdata2$se.fit)

#Plot these predictions with their uncertainties
#Plot these predictions with their uncertainties
ggplot(data=graphdata2)+
geom_line(aes(x=Explanatory1, y=fit, color=as.factor(Explanatory2)), size=2)+
geom_errorbar(aes(x=Explanatory1, y=fit, color=as.factor(Explanatory2), ymin=LL, ymax=UL),width=0.1, size=2)+
geom_point(aes(x=Explanatory1, y=fit, color=as.factor(Explanatory2)), color=”black”, size=3)