Search code examples
rgam

Plotting smooth functions from a gam (using type = 'terms')


This is more of a follow up from a similar question asked recently, so hopefully this is a better/less vague question.

I have created a GAM and with to plot both smooth functions (on the same plot or two separate), what i'm failing with is how to plot the 2 columns i get in my predictions. I need to keep month in my model for creating predictions due to the seasonal trend later down the line.

mod = gam(co2 ~ s(timeStep, k = 200, bs = "cs") + s(month, k = 12, bs = "cc"), 
            data = carbonD,
            family = gaussian(link = "identity"))

#predictions
preds = predict(carbonD_model3, newdata, type = 'terms', se.fit = TRUE)
preds$fit
    s(timeStep)   s(month)
1   -21.023636218 -0.44138402
2   -20.710943557 -0.36466359
3   -20.512344518  0.04800245
4   -20.532656726  1.15111508
5   -20.763446687  1.92491535
6   -21.120504411  1.80493059


#attempt at plotting but gives aesthetics errors
ggplot(newdata, aes(timeStep, co2)) + 
   geom_line(aes(timeStep, preds), col = 'red') 

Also aware that this can be done someway like this (below), but would like to get my predictions working using this method is possible.

plot(mod)

enter image description here


Solution

  • This works for me:

    data(mtcars)
    library(mgcv)
    #> Loading required package: nlme
    #> This is mgcv 1.8-40. For overview type 'help("mgcv-package")'.
    library(ggplot2)
    library(dplyr)  
    #> 
    #> Attaching package: 'dplyr'
    #> The following object is masked from 'package:nlme':
    #> 
    #>     collapse
    #> The following objects are masked from 'package:stats':
    #> 
    #>     filter, lag
    #> The following objects are masked from 'package:base':
    #> 
    #>     intersect, setdiff, setequal, union
    m1 <- gam(mpg ~ s(hp) + s(wt), data=mtcars)
    
    preds <- predict(m1, type="terms")
    mf <- model.frame(m1)
    mf <- bind_cols(mf, preds)
    
    
    ggplot(mf, aes(x=hp, y=`s(hp)`)) + 
      geom_line() 
    

    ggplot(mf, aes(x=wt, y=`s(wt)`)) + 
      geom_line()
    

    Created on 2022-06-27 by the reprex package (v2.0.1)