Home > Mobile >  How do you plot smooth components of different GAMs in same panel?
How do you plot smooth components of different GAMs in same panel?

Time:02-19

I have two GAMs which have the same predictor variables but different independent variables. I would like to combine the two GAMs to a set of plots where the smooth component (partial residuals) of each predictor variable are in the same panel (differentiated with e.g. color). Reproducible example:

# Required packages
require(mgcv)
require(mgcViz)

# Dataset
data("swiss")

# GAM models
fit1 <- mgcv::gam(Fertility ~ s(Examination)   s(Education), data = swiss)
fit2 <- mgcv::gam(Agriculture ~ s(Examination)   s(Education), data = swiss)

# Converting GAM objects to a gamViz objects
viz_fit1 <- mgcViz::getViz(fit1)
viz_fit2 <- mgcViz::getViz(fit2)

# Make plotGAM objects
trt_fit1 <- plot(viz_fit1, allTerms = T)   l_fitLine()
trt_fit2 <- plot(viz_fit2, allTerms = T)   l_fitLine()

# Print plots
print(trt_fit1, pages = 1)
print(trt_fit2, pages = 1)

Plot of fit1 looks like this:

trt_fit1

And fit2 like this:

trt_fit2

So I would like to combine the two Examinations into one panel, and the two Educations into another one, showing the independent variable (from different GAMs) with different color/linetype.

CodePudding user response:

If you want them in the same plot, you can pull the data from your fit with trt_fit1[["plots"]][[1]]$data$fit and plot them yourself. I looked at the plot style from the mgcViz github. You can add a second axis or scale as necessary.

library(tidyverse)
exam_dat <- 
  bind_rows(trt_fit1[["plots"]][[1]]$data$fit %>% mutate(fit = "Fit 1"), 
            trt_fit2[["plots"]][[1]]$data$fit %>% mutate(fit = "Fit 2"))
  

ggplot(data = exam_dat, aes(x = x, y = y, colour = fit))  
  geom_line()  
  labs(x = "Examination", y = "s(Examination)")   
  theme_bw()  
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

To simply get them on the same panel, you could use gridExtra as fit1 and fit2 have a ggplot object.

gridExtra::grid.arrange(
  trt_fit1[["plots"]][[2]]$ggObj, 
  trt_fit2[["plots"]][[2]]$ggObj, 
  nrow = 1)

Created on 2022-02-18 by the reprex package (v2.0.1)

  • Related