Search code examples
rggplot2data-visualizationfacet

facet_wrap with layout like facet_grid


Using facet_grid wraps panels according to the factor levels in the variables provided, even if there is no data present for a given combination. This is the behaviour I am after.

Unfortunately, the y-axes scales can not be made independent on the individual panel level (see here and here). For that, you must use facet_wrap.

facet_wrap, however, doesn't provide the same layout as facet_grid, and only displays the panels that have values to be plotted.

How can I keep the facet_grid-like layout but with independent y-axis scales? It is okay if the panels without data are blank/void as long as they occupy the appropriate space.

Reproducible example:

library(ggplot2)
set.seed(1)

# Generate data
test <- data.frame(x = c(rep(1, 6), rep(2, 6)), 
                   facet_1 = rep(c("A", "A", "A", "B", "B", "C"), 2),
                   facet_2 = rep(c("B", "C", "D", "C", "D", "D"), 2),
                   y = c(1e0, 1e1, 1e2, 1e3, 1e4, 1e5, rnorm(1, 1e0, 1e0*.34), rnorm(1, 1e1, 1e1*.34), rnorm(1, 1e2, 1e2*.34), rnorm(1, 1e3, 1e3*.34), rnorm(1, 1e4, 1e4*.34), rnorm(1, 1e5, 1e5*.34)))

# facet_grid - Shows blank panels B-B, B-C, and C-C. This is what I want.
#            - Does NOT scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_grid(facet_2 ~ facet_1, scales = "free") +
  geom_line()

facet_grid example

# facet_wrap - Does NOT show blank panels B-B, B-C, and C-C.
#            - Does scale y appropriately at the individual panel level.
ggplot(test, aes(x = x, y = y)) +
  facet_wrap(vars(facet_1, facet_2), scales = "free") +
  geom_line()

facet_wrap example


Solution

  • You can complete the missing combination and then plot.

    library(ggplot2)
    
    tidyr::complete(test, facet_1, facet_2, fill = list(x = 0, y = 0)) %>%
    #Keeping them as NA would give a blank plot
    #tidyr::complete(test, facet_1, facet_2) %>%
       ggplot() + aes(x = x, y = y) +
       facet_wrap(vars(facet_1, facet_2), scales = "free") +
       geom_line()
    

    enter image description here

    This would give you a warning as there is only one observation in those 3 groups.