简体   繁体   中英

Nested facet_wrap() in ggplot2

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: 在此处输入图片说明

But, if I want to plot four of these next to each other automatically in a 2x2 grid (ie 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:

在此处输入图片说明

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)

在此处输入图片说明

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM