Search code examples
rplotvisualizationmgcv

How to combine and save vis.gam plots?


I have created two plots using the vis.gam function. I'm encountering difficulties when attempting to combine and save them. I've attempted various methods such as grid.arrange, ggarrange, and plot_layout, but none seem to work effectively. Although I can arrange them using par(mfrow=c(1, 2)), I prefer using a standard function that allows further formatting. As for saving, the code I tried hasn't been successful. Could someone help with the code to combine and save these plots? My code for saving plots

png("fig.png", width = 465, height = 225, res = 300)
dev. Off()

My code to produce plots

p1 <- vis.gam(mod1, view = c("x1",  "x2"), theta = 120, plot. Type = "persp")
p2 <- vis.gam(mod1, view = c("x3",  "x4"), theta = 120, plot. Type = "persp")

enter image description here


Solution

  • If you want to easily combine the plots with ultimate flexibility, you can use patchwork:

    library(ggplot2)
    library(patchwork)
    
    p1 <- wrap_elements(panel = ~vis.gam(g, view = c("x1",  "x2"), 
                                         theta = 120, plot.type = "persp"))
    p2 <- wrap_elements(panel = ~vis.gam(g, view = c("x3",  "x4"), 
                                         theta = 35, plot.type = "persp"))
    ggsave("fig.png", p1 + p2)
    

    fig.png enter image description here


    Data used

    The hardest part of answering this question was creating a model from scratch that matched the OP's names, as there was no reproducible example:

    library(mgcv)
    
    set.seed(0)
    n <- 200
    sig2 <- 4
    x1 <- runif(n, 0, 1)
    x2 <- runif(n, 0, 1)
    x3 <- runif(n, 0, 1)
    x4 <- runif(n, 0, 1)
    y <- x0^2 + x1 * x2 * x4
    mod1 <- gam(y ~ s(x1, x2, x3, x4))