Nested facet_wrap() in ggplot2

Viewed 3485

Say I have these data:

set.seed(100)
mydf<-
data.frame(
day = rep(1:5, each=20),
id = rep(LETTERS[1:4],25),
x = runif(100),
y = sample(1:2,100,T)
)

If I just want to plot all five days of id=="A" using facet_wrap(), we do like this:

ggplot(mydf[mydf$id=="A",], aes(x,y))  +  
       geom_tile() +
       facet_wrap(~day,ncol=1) 

Gives: enter image description here

But, if I want to plot four of these next to each other automatically in a 2x2 grid (i.e. showing A,B,C,D), is that possible using a nested facet? I tried doing multiple variables in the function like this:

ggplot(mydf, aes(x,y))  +  
  geom_tile() +
  facet_wrap(~ day+id) 

but this gives this:

enter image description here

I'm looking for a nested approach. Five faceted rows by day in each panel with each plot in columns/rows by id. Obviously for a small number of plots I could save individually and arrange with grid.arrange etc., but in the real data I have many plots so want to automate if possible.

EDIT:

In response to comment - this is the sort of desired output:

enter image description here

2 Answers
Related