0

Is it possible to facet a set of faceted graphs? I'd love to facet_wrap a set of faceted graphs.

The best I came up with is a cowplot solution that doesn't work all that well. Ideally, we wouldn't have to write separate graph objects.

library(ggplot2)
library(cowplot)


g1 <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + facet_wrap(~am)
g2 <- ggplot(mtcars, aes(disp, cyl)) + geom_point() + facet_wrap(~am)
plot_grid(g1, g2, labels = c("Facet Group 1", "Facet Group 2"))

Created on 2018-10-08 by the reprex package (v0.2.0).

EDIT:

I appreciate the "reshape the data" approaches below, but they don't quite work for what I'm trying to accomplish. I want to create a hierarchy of facets, where "Facet Group 1 / Facet Group 2" is a higher level than am. The "reshape the data" approach "melts" the hierarchy, if you will.

EDIT 2:

Here's the hack in which I make four separate faceted graph, then lay them out in LaTeX. Would still love a ggplot solution if it's out there!

enter image description here

Alex Coppock
  • 2,122
  • 3
  • 15
  • 31

2 Answers2

1

The easiest solution I can think of is modifying the data itself. But maybe there is a less "hackish" solution to this problem.

library(tidyverse)

data <- mtcars %>%
  dplyr::select(disp, mpg, cyl, am) %>%
  tidyr::gather(., key = v.facet, value, mpg:cyl)

ggplot(data, aes(disp, value)) + 
  geom_point() + 
  facet_wrap(am ~ v.facet, nrow = 1)

Created on 2018-10-09 by the reprex package (v0.2.1)

Indrajeet Patil
  • 4,673
  • 2
  • 20
  • 51
1

You can have multiple levels of facets. Here we just need to reshape your data a bit

library(ggplot2)
library(dplyr)
library(tidyr)

mtcars %>% 
  select(disp, am, mpg, cyl) %>% 
  gather("measure", "y", mpg, cyl) %>% 
  ggplot(aes(disp, y)) + 
  geom_point() + facet_wrap(~measure+am,nrow = 1)

enter image description here

But if you you really need to control exactly how far each of the strips spreads, you're probably not going to have a good time.

MrFlick
  • 195,160
  • 17
  • 277
  • 295