rggplot2facet-wrapfacet-grid

How to force facet_wrap to use the defined number of columns?


I have two faceted graphs (A, ncol = 3 ; B, ncol = 2) that I want to merge together. When merging (with ggarrange), I want the facets of each graphs to be aligned (ie, I want to force facet_wrap to use the argument ncol=X, even if the number of facets is inferior to X).

Any idea how I could make it?

#reprex
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
df <- ToothGrowth
bp <- ggplot(df, aes(x=dose, y=len, group=dose)) + geom_boxplot(aes(fill=dose)) 

a <- bp + facet_wrap(~ dose, ncol=3)
b <- bp + facet_wrap(~ supp, ncol=3)
grid.arrange(a,b,nrow=2)

what I get:

get

what I want:

need


Solution

  • One quick and easy option would be to use ggh4x::facet_manual which via the design= argument allows to place panels individually and which easily allows to add empty panels. However, this will still place the legend for the second row at the right of the panels.

    library(ggplot2)
    library(ggh4x)
    
    ToothGrowth$dose <- as.factor(ToothGrowth$dose)
    df <- ToothGrowth
    bp <- ggplot(df, aes(x = dose, y = len, group = dose)) +
      geom_boxplot(aes(fill = dose))
    
    a <- bp + facet_manual(~dose, design = matrix(seq(3), ncol = 3))
    b <- bp + facet_manual(~supp, design = matrix(seq(3), ncol = 3))
    
    gridExtra::grid.arrange(a, b, nrow = 2)