> # simulate some data...
> dat <- gamSim(1,n=400,dist="normal",scale=2)
> # fit model&plot
> library(mgcv)
> library(splines)
> b0 <- gam(y~s(x1),data=dat)
> plot(b0)
Following the code above, I can get a plot like this: enter image description here
Now, I want to get a similar plot using the ns() function in GAM:
> b1 <- gam(y ~ ns(x1), data=dat)
> plot(b1)
But when I run the code in R, it shows "No term to plot", so I would like to know how to plot this picture? Thanks!
Because
ns()
is not a (penalised) spline indicated bys()
,te()
,t2()
orti()
, it is not a member of class"mgcv.smooth"
. When you plot the fitted GAM object, the code looks to see if there are any mgcv smooths to plot. All other terms in the model are parametric terms, including your natural spline. If you dosummary(b1)
you'll see thens()
term in the Parametric effects section of the output.Basically,
gam()
is just looking at your model as if it were a bunch of linear parametric terms. It doesn't know that those terms in the model matrix map to basis functions and hence to a natural spline.Visualisation is not easy;
plot(b1, all.terms = TRUE)
will plot the linear effects of each basis function, so at least you see something, but typically this is not what you want. You will have to predict from the model over the range of the covariatex1
and then plot the predicted values against the grid ofx1
values.This begs the question; what were you expecting
gam()
to do with thens()
basis?