¿Es posible trazar los componentes suaves de un juego en ggplot2?

Estoy ajustando un modelo usandogam desde elmgcv empacar y almacenar el resultado enmodel y hasta ahora he estado mirando los componentes lisos utilizandoplot(model). Recientemente he empezado a usar ggplot2 y me gusta su salida. Así que me pregunto, ¿es posible trazar estos gráficos usando ggplot2?

Aquí hay un ejemplo:

x1 = rnorm(1000)
x2 = rnorm(1000)
n = rpois(1000, exp(x1) + x2^2)

model = gam(n ~ s(x1, k=10) + s(x2, k=20), family="poisson")
plot(model, rug=FALSE, select=1)
plot(model, rug=FALSE, select=2)

Y estoy interesado ens(x1, k=10) ys(x2, k=20) no en el ajuste.

Respuesta parcial:

Cavé más profundo enplot.gam ymgcv:::plot.mgcv.smooth y construí mi propia función que extrae los efectos predichos y los errores estándar de los componentes suaves. No maneja todas las opciones y casos deplot.gam así que solo lo considero una solución parcial, pero funciona bien para mí.

EvaluateSmooths = function(model, select=NULL, x=NULL, n=100) {
  if (is.null(select)) {
    select = 1:length(model$smooth)
  }
  do.call(rbind, lapply(select, function(i) {
    smooth = model$smooth[[i]]
    data = model$model

    if (is.null(x)) {
      min = min(data[smooth$term])
      max = max(data[smooth$term])
      x = seq(min, max, length=n)
    }
    if (smooth$by == "NA") {
      by.level = "NA"
    } else {
      by.level = smooth$by.level
    }
    range = data.frame(x=x, by=by.level)
    names(range) = c(smooth$term, smooth$by)

    mat = PredictMat(smooth, range)
    par = smooth$first.para:smooth$last.para

    y = mat %*% model$coefficients[par]

    se = sqrt(rowSums(
      (mat %*% model$Vp[par, par, drop = FALSE]) * mat
    ))

    return(data.frame(
      label=smooth$label
      , x.var=smooth$term
      , x.val=x
      , by.var=smooth$by
      , by.val=by.level
      , value = y
      , se = se
    ))
  }))
}

Esto devuelve un marco de datos "fundido" con los componentes suaves, por lo que ahora es posible utilizarggplot con el ejemplo anterior:

smooths = EvaluateSmooths(model)

ggplot(smooths, aes(x.val, value)) + 
  geom_line() + 
  geom_line(aes(y=value + 2*se), linetype="dashed") + 
  geom_line(aes(y=value - 2*se), linetype="dashed") + 
  facet_grid(. ~ x.var)

Si alguien sabe un paquete que permite esto en el caso general, estaría muy agradecido.

Respuestas a la pregunta(2)

Su respuesta a la pregunta