-3

I am using facet_grid to co-visualize data according to two factors. One factor as too many levels to fit in one row. I would therefore like to achieve something like facet_wrap, but with 2 dimensions:

  1. Can facet_wrap be used with two factors?
  2. Can facet_grid be used to wrap over one factor?

The output should look something like

A    B    C
.    .    .  1
.    .    .  2

D    E       
.    .       1
.    .       2

Factor 1 as 5 levels A-E, wrapped on 2 rows, and Factor 2 as two levels 1-2, repeated on each row.

Here is a practical example to play with:

library(ggplot2)
df <- data.frame(y=rnorm(1000), f1=rep(1:10, 100), f2=rep(1:2, each=500))
ggplot(df, aes(x=x)) + geom_histogram() + facet_grid(f2~f1)

I would like to split the image in two, with the five first levels on top, and the last five under, while maintaining the 1 and 2 rows for each.

Many thanks for your consideration!

Julien
  • 13
  • 2
  • 1
    Please provide a reproducible example – Koundy Aug 17 '15 at 09:30
  • Can't help more without reproducible data, but you may want to explore splitting those into two plots, and arranging them into one display. See http://stackoverflow.com/questions/30015175/multiple-row-of-charts-in-ggplot-without-using-facet for close (but not exact) example of approach – Ricky Aug 17 '15 at 09:31
  • 1
    facet_wrap can be used with multiple factors, e.g. `facet_wrap(~a+b)` – baptiste Aug 17 '15 at 09:38
  • Unfortunately this does not preserve the grid layout, it simply list all combination of factors, resulting in something like A1 A2 B1 B2 etc. – Julien Aug 17 '15 at 11:03

1 Answers1

0

There is not built in functionality to do this in ggplot2, but you can approximate this behavior by using grid.arrange from gridExtra:

library(gridExtra)
p1 <- ggplot(df[df$f1 %in% 1:5,], aes(x=y)) + 
    geom_histogram() + 
    facet_grid(f2~f1)
p2 <- ggplot(df[df$f1 %in% 6:10,], aes(x=y)) + 
    geom_histogram() + 
    facet_grid(f2~f1)

grid.arrange(p1,p2,nrow = 2)

The alignment between the two separate plots will generally not be perfect. It can be aligned more precisely, but not without some effort (detailed fiddling in grid).

joran
  • 169,992
  • 32
  • 429
  • 468