Function to plot multiple GAM parametric effects?

161 Views Asked by At

I created several GAMs which include non-smoothed (parametric), continuous variables (besides the s() parameters).

I would like to plot the parametric, continuous variables of two models together. For example:

g1 <- x ~ s(y) + z 
g2 <- x ~ s(y1) + z

I want to have z (continuous variable) from models g1 and g2 in the same plot, similar to what we can do with the gratia::compare_smooths(). But this function works only for the smoothed parameters, as far as I know. I see only the option for plotting them individually. Any suggestions?

Additionally, if I have two models with the formula:

g3 <- x ~ s(y) + z 
g4 <- x ~ s(y1) + z1

Is it possible to get z and z1 in the same plot?

Thanks in advance!

1

There are 1 best solutions below

1
On

You could use any of the many packages that produce predicted effects (I use ggeffects below, but others such as effects and marginaleffects would likely work too, though with a different workflow. You can get the effect of z from each model, put the two datasets together identifying which model each effect comes from and then make the plot:

data(mtcars)
library(mgcv)
library(dplyr)
library(ggplot2)
g1 <- gam(qsec ~ s(wt) + hp, data=mtcars)
g2 <- gam(qsec ~ s(mpg) + hp, data=mtcars)

library(ggeffects)
gp1 <- ggpredict(g1, "hp") %>% mutate(model = "Model 1")
gp2 <- ggpredict(g2, "hp") %>% mutate(model = "Model2")
gp <- bind_rows(gp1, gp2)


ggplot(gp, aes(x=x, y=predicted, ymin=conf.low, ymax=conf.high, fill=model, colour=model)) + 
  geom_ribbon(alpha=.2, col="transparent") + 
  geom_line() + 
  theme_classic()

Created on 2023-04-18 with reprex v2.0.2