Search code examples
rggplot2plotvisreg

Controlling facet column number with visreg


While I am enjoying using package visreg to visualize my regressions, there's one thing that I can't yet control: the number of columns when faceting. See the following factor-by-curve generalized additive regression for example:

library(dplyr)
library(mgcv)
library(visreg)
data(airquality)
test <- gam(
    Ozone ~ s(Temp, by = Month),
    data = airquality %>% mutate(Month = as.factor(Month))
)

If I do

visreg(test, xvar = "Temp", by = "Month", gg = TRUE)

I get a 1-row, 5-column factor-by-curves.

enter image description here

Funnily enough, if I take the gg = TRUE out, it becomes 2-row. But whichever is the case I would like to be able to control the number of columns and rows when faceting. So far I have been unsuccessful, by either manipulating the ellipsis argument of visreg or by directly trying to manipulate the resulting ggplot object.

So for example, if I wanted to do visreg with gg = TRUE with 3-row, 2-column, what would be my best chance---or is there another package that is recommended?


Solution

  • You can just modify the ggplot object and add facet_wrap in the usual way:

    p <- visreg(test, xvar = "Temp", by = "Month", gg = TRUE)
    p + facet_wrap(vars(Month), nrow = 3)
    

    enter image description here

    You don't actually need to create p first, this gives the same result:

    visreg(test, xvar = "Temp", by = "Month", gg = TRUE) +
      facet_wrap(vars(Month), nrow = 3)