Lenn
Lenn

Reputation: 1469

Combine GAM-smooths of multiple covariates in one plot in R

I have a list of dataframes in R. Each element of the list is a dataframe with the same covariates. However, the values of the covariates differ for each dataframe as I applied a smoothing algorithm with different combinations for each of them.

I then fitted a gam for each dataframe. And what I would like to do now is to make one plot for each covariate with the smoothing lines for each dataframe

Update

Just to share some code and make it a little clearer: And now I'd like to do something like a facet-plot. Where each plot contains the smooths for a covariate (x1 and x2) of the different gams. I hope this makes sense...

library(mgcv)

# make list of dataframes for storing data
data = vector("list", length = 3)

#  fill the list
for(i in seq_along(data)){
  data[[i]] = gamSim(n = 200, dist = "normal", scale = 2)
}

# fit the gams
gam_models = vector("list", length(data))
for(i in seq_along(data)){
  res = gam(y ~ s(x0) + s(x1) + s(x2), data = data[[i]])
  gam_models[[i]] = res
  par(mfrow = c(1,2))
  plot(res, all.terms=TRUE, main="Name of Covariate")
}

Upvotes: 1

Views: 1491

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

I'm not entirely clear on what you are asking. The sample code you provided in your most recent edit seems to do exactly what you're after.

You've mentioned facets, so perhaps you're after a ggplot solution? If so, here is an option using some of the plotting methods provided by the mgcViz package.

library(mgcViz)
library(grid)
library(tidyverse)
lst <- imap(
    setNames(gam_models, paste("Model", seq_along(gam_models), "covariates")),
    function(fit, nm) {
        terms <- fit %>% pluck("terms") %>% attr("term.labels")
        map(
            c(nm, rep("", length(terms) - 1)),
            ~textGrob(.x, hjust = 1)) %>%
        append(map(
            seq_along(terms), ~
            plot(sm(fit %>% getViz(), .x)) +
            l_fitLine(colour = "black") +
            l_ciLine(colour = "black", linetype = 2) +
            l_rug(mapping = aes(x = x, y = y), alpha = 0.8)))
    }) %>%
    unlist(recursive = FALSE)

gridPrint(grobs = lst, ncol = 3, heights = rep(c(1, 3), length(gam_models)))

enter image description here

Explanation: The idea is to build a list of ggplot objects, where rows correspond to the different GAMs, and columns to the covariates. Note that this assumes that all GAMs have the same number of covariates. To adjust for more models & covariates, you'd need to change the hard-coded parameters for ncol and heights in gridPrint.

Upvotes: 1

Related Questions