mfasiolo / mgcViz

An R package for interactive visualization of GAM models
https://mfasiolo.github.io/mgcViz/
76 stars 9 forks source link

Add function to get smooth effect plots on response scale #52

Open mfasiolo opened 5 years ago

mfasiolo commented 5 years ago

At the moment we need to use the trans function to plot on response scale. This can be quite laborious. Maybe it is possible to do something automatically, possibly using the derivatives of the inverse link to transform the standard errors as well. Actually it might be possible to do this for general transformations, with transformation to response scale being a special case.

Example:

#######
# Simulate some data
library(mgcViz)
n  <- 2e3
x1 <- rnorm(n)
x2 <- rnorm(n)
x3 <- rnorm(n)
dat <- data.frame("x1" = x1, "x2" = x2, "x3" = x3,
                  "y" = abs( 0.1 + sin(x1) + 0.5 * x2^2 + 0.2*x3 + 0.2*rnorm(n) ))
b <- gamV(y ~ s(x1, x2) + s(x3), data = dat, family = Gamma(link=log))

# Plot s(x1, x2) on link scale
plot(sm(b, 1))

# Plot s(x1, x2) on response scale
plot(sm(b, 1), 
     trans = function(x){ 
       b$family$linkinv(coef(b)[1] + x)
       })

# We added the intercept and inverted the link function (if you use the identity link this is not necessary).
# Also, above s(x3) is left to zero, so we are conditioning on x3 being approximately 0 as can be seen from plot(sm(b, 2))

# To condition on a different value of x3 we must use predict.
# Here s3 is the value of s(x3) at x3 = 2 (the values of x1 and x2 do not matter here)
s3 <- predict(b, newdata = data.frame(x1 = 0, x2 = 0, x3 = 2), type = "terms")[2]

# Plotting on response scale
plot(sm(b, 1), 
     trans = function(x){
       b$family$linkinv(coef(b)[1] + s3 + x)
       })
NeutralKaon commented 2 years ago

I'm looking for a good way to do this with a general model but unfortunately haven't found one. Am I right in thinking that there is no nice equivalent to plain 'old viz.gam(..., type = "response") with mgcViz?

mfasiolo commented 2 years ago

Yes unfortunately at the moment there is no easy way of doing this in mgcViz.