# [R] 2 bands (confidence and prediction) on the same GAM plot?

varin sacha v@r|n@@ch@ @end|ng |rom y@hoo@|r
Mon May 1 22:16:51 CEST 2023

```Dear R-experts,

Here below my R code (toy example) working! The only thing missing is in my GAM plot: I would like to get on the same graph the 2 bands (prediction and confidence bands) like in my lm model graph!
Is it possible? How to get that?

##############################################################################
#Data
a=c(23,43,23,45,46,56,76,87,98,73,36,48,100,134,21,12,25,43,21,73,48,57,69)
x1=c(0.1,0.3,0.4,0.7,0.1,0.5,0.9,0.1,0.2,0.3,0.4,0.5,0.9,0.5,0.76,0.45,0.98,0.23,0.41,0.38,0.36,0.67,0.89)
x2=c(1.2,2.1,1.8,1.6,1.9,2.9,4.9,5.2,6.4,2.7,8.9,6.7,4.5,3.8,4.5,9.8,6.7,8,5,9,4.7,6.98,9.9)

data=data.frame(a,x1,x2)

#Fit lm model
model=lm(a~x1+x2)

#add predictions
pred.int=predict(model, interval="prediction")
mydata=cbind(data,pred.int)

#regression line + Cis for x1
library("ggplot2")
p=ggplot(mydata,aes(x1,a)) + geom_point() + stat_smooth(method=lm)

#add prediction intervals for x1
p + geom_line(aes(y=lwr),color="red",linetype="dashed") + geom_line(aes(y=upr),color="red", linetype="dashed")

#regression line + Cis for x2
library("ggplot2")
p=ggplot(mydata,aes(x2,a)) + geom_point() + stat_smooth(method=lm)

#add prediction intervals for x2
p + geom_line(aes(y=lwr),color="red",linetype="dashed") + geom_line(aes(y=upr),color="red", linetype="dashed")

###GAM
##libraries
library(ggplot2)
library(mgcv)

##fit and plot
model1=gam(a~s(x1)+s(x2))
plot(model1, pages=1,residuals=TRUE,all.terms=TRUE,shade=TRUE,shade.col=2)
##############################################################################

```

More information about the R-help mailing list