Skip to content
Prev 385603 / 398503 Next

facet_wrap(nrow) ignored

Dear Ivan,

I don't think it is possible to force a number of rows - but I'm 
honestly just guessing.

What you can do is to add an empty plot. Here I use cowplot, but 
gridExtra should also work well.

I add an indication of the row number for the plot to the initial 
data.frame, and loop over these.

In the first variant, I add an unused factor to the grp which creates an 
empty facet. I personally think this looks a little confusing, so in the 
second variant, I add a number of empty plots.

HTH
Ulrik

```
mydf <- data.frame(
   grp = rep(letters[1:6], each = 15),
   cat = rep(1:3, 30),
   var = rnorm(90),
   row_num = rep(c(1, 1, 2, 3, 4, 5), each = 15)
)

s_mydf <- split(mydf, mydf$row_num)

plots_mydf <- lapply(s_mydf, function(x){
   # Ensure no unused factors
   x$grp <- droplevels.factor(x$grp)
   if(length(unique(x$grp)) == 1){
     x$grp <- factor(x$grp, levels = c(unique(x$grp), ""))
   }
   ggplot(data = x, aes(x = cat, y = var)) + geom_point() +
     facet_wrap(~grp, drop=FALSE)
})

cowplot::plot_grid(plotlist = plots_mydf, nrow = 5)

# Maybe more elegant output
plots_mydf <- lapply(s_mydf, function(x, ncol = 2){
   # Ensure no unused factors
   x$grp <- droplevels.factor(x$grp)
   x <- split(x, x$grp)

   p <- lapply(x, function(x){
     ggplot(data = x, aes(x = cat, y = var)) + geom_point() +
       facet_wrap(~grp)
   })

   if(length(p) < ncol){
     pe <- rep(list(ggplot() + theme_void()), ncol - length(p))
     p <- c(p, pe)
   }
   cowplot::plot_grid(plotlist = p, ncol = ncol)
})

cowplot::plot_grid(plotlist = plots_mydf, ncol = 1)

# Or if you prefer not to split the plots on the same row
plots_mydf <- lapply(s_mydf, function(x, ncol = 2){

   p <- list(ggplot(data = x, aes(x = cat, y = var)) + geom_point() +
     facet_wrap(~grp))

   if(length(unique(x$grp)) < ncol){
     pe <- rep(list(ggplot() + theme_void()), ncol - length(p))
     p <- c(p, pe)
   }else{
     ncol <- 1
   }
   cowplot::plot_grid(plotlist = p, ncol = ncol)
})

cowplot::plot_grid(plotlist = plots_mydf, ncol = 1)

```
On 2020-09-09 17:30, Ivan Calandra wrote: