Reputation: 14222
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)
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:
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:
Upvotes: 3
Views: 3985
Reputation: 77124
try this,
p <- ggplot(mydf, aes(x,y)) +
geom_tile() +
facet_wrap(~ day, ncol=1)
library(plyr)
lp <- dlply(mydf, "id", function(d) p %+% d + ggtitle(unique(d$id)))
library(gridExtra)
grid.arrange(grobs=lp, ncol=2)
Upvotes: 3
Reputation: 199
Here is a quick attempt using the multiplot
function found here
ids = levels(as.factor(mydf$id))
p = vector("list", length(ids))
names(p) = ids
for(i in 1:length(ids)){
p[[i]] = ggplot(mydf[mydf$id == ids[i],], aes(x,y)) + geom_tile() + ggtitle(paste(ids[i])) + facet_wrap(~day, ncol=1)
}
multiplot(p$A, p$B, p$C, p$D, cols = 2)
Upvotes: 2