Free space and scales in ggplot facets

I'm interested in facet plots which would have both free scales (because units of different facet groups are different) and variable facet width or height (because different facets have different numbers of observations plotted in them). Currently, I'm able to achieve either goal but not both. Here's a minimal example:

library(tidyverse)
        
sample_data <- data.frame(outcome = rep(letters[1:6], 2),
                          value = rep(c(1:2, 100*1:4), 2),
                          units = rep(c("days", "days", "pax", "pax", "pax", "pax"), 2),
                          year = rep(2020:2021, each = 6)) 

p <- ggplot(sample_data, aes(x = outcome, y = value)) + geom_col() + coord_flip()

Using facet_grid and the space = "free" option, I'm able to get the variable facet dimensions:

p + facet_grid(units~year, scales = "free", space = "free") 

enter image description here

Using facet_wrap and the scales = "free" option, I'm able to get the variable units.

p + facet_wrap(units~year, scales = "free")

enter image description here

Any idea how to get both variable facet size and free scales (preferably with the facet header structure of facet_grid)?


You can use the independent argument in ggh4x::facet_grid2() to achieve this. Note that you cannot have both free axes and independent scales in the same dimension.

library(tidyverse)

sample_data <- data.frame(outcome = rep(letters[1:6], 2),
                          value = rep(c(1:2, 100*1:4), 2),
                          units = rep(c("days", "days", "pax", "pax", "pax", "pax"), 2),
                          year = rep(2020:2021, each = 6)) 

ggplot(sample_data, aes(x = value, y = outcome)) + 
  geom_col() +
  ggh4x::facet_grid2(
    units ~ year,
    scales = "free", space = "free_y",
    independent = "x"
  )

Created on 2022-01-18 by the reprex package (v2.0.1)

Disclaimer: I wrote ggh4x.