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

84 views Asked by At

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

2

There are 2 answers

0
stefan On BEST ANSWER

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)

2
G. Grothendieck On

Using cowplot define the bottom row and then nest that within the main grid. You may need to adjust the 2.3 depending on how you are rendering it.

library(cowplot)

bottom_row <- plot_grid(b, NULL, ncol = 2, rel_widths = c(2.3, 1))
plot_grid(a, bottom_row, ncol = 1)

This is what it looks like using Rgui on Windows if the graphics window is fully expanded. rel_widths = c(2.7, 1) worked better if not expanded.

screenshot