1

Is there a way to get ggplot2::facet_wrap() to have a facet span on several rows?

I'm thinking of something very similar to what could be achieved with {patchwork} (example).

Here is a very lame example with 3 facets:

library(tidyverse)
mtcars %>% 
  select(cyl, am, gear, carb) %>% pivot_longer(-cyl) %>% 
  ggplot(aes(fill=name, x=value)) + 
  geom_bar(position="dodge") +
  facet_wrap("cyl", scale="free")

Created on 2021-07-05 by the reprex package (v2.0.0)

In this example, how could I have these facets on 2 rows with first cyl==4&6 on 1 column each, and then cyl==8 which would span on 2 columns?

Here is my expected output (beware of my mighty MS Paint skills): enter image description here

Dan Chaltiel
  • 7,811
  • 5
  • 47
  • 92
  • [This](https://stackoverflow.com/questions/52341385/how-to-automatically-adjust-the-width-of-each-facet-for-facet-wrap/52422707) may be of some help – akrun Jul 05 '21 at 19:57

1 Answers1

3

I've recently put up a manual facets function in ggh4x on github. It allows you to do pretty much exactly what your expected output looks like. (disclaimer: I'm the author of ggh4x)

library(tidyverse)
library(ggh4x) # devtools::install_github("teunbrand/ggh4x")

mtcars %>% 
  select(cyl, am, gear, carb) %>% 
  pivot_longer(-cyl) %>% 
  ggplot(aes(fill=name, x=value)) + 
  geom_bar(position="dodge") +
  facet_manual("cyl", scale="free", design = matrix(c(1,3,2,3), 2, 2))

Created on 2021-07-13 by the reprex package (v1.0.0)

P.S. because this facet function is new, it might have some bugs I'm unaware of. Please let me know if you find some.

teunbrand
  • 33,645
  • 4
  • 37
  • 63