0

Does anyone know how to visualize the smooth component of gam models in R very well? I would really like to visualize something like the output of the function visreg. This code below illustrates my problem

library(gam)

f=function(v){exp(v)}
n=100
x=runif(n)
t=runif(n)
y=x+f(t)+rnorm(n, sd=0.1)

fit=gam(y~x+s(t))

plot(t,y)
lines(t,as.numeric(fit$smooth))

#want something more like
library(visreg)
visreg(fit)
justin1.618
  • 691
  • 5
  • 15

1 Answers1

2

You could use the plotting method for gam objects, but you'd have to use the data parameter of gam:

library(gam)

f <- function(v){exp(v)}
n <- 100
x <- runif(n)
t <- runif(n)
y <- x+f(t)+rnorm(n, sd=0.1)
DF <- data.frame(y, x, t)

fit <- gam(y~x+s(t), data = DF)
layout(t(1:2))
plot(fit, se=TRUE)

resulting plot

See help("plot.gam") for other options.

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Thank you. Do you know why the scale is off in the plots? The range of f(t) is from about 1 to 2.75 but in the graphs, s(t) is from less than -0.5 to 1? Also, do you know how to add the t,y points? I tried points(t,y) but that didnt work. Thanks for your help! – justin1.618 May 20 '15 at 05:23
  • 1
    You should do some reading about GAMs. Smoothers are centered. – Roland May 20 '15 at 07:07