ggforce facet_wrap_paginate with number of plots not matching nrow and ncol

909 Views Asked by At

I have a problem with the facet_wrap_paginate function: I have several groups of diagrams. The number of diagrams in each group varies. When I use facet_wrap_paginate to plot each group in 5x4 diagrams onto one single pdf, I get an error if the last pdf page has too few plots, so that the first row of plots is not "filled".

e.g. one group of plots contains 22 plots, so 20 plots go on the first page and the second page only has 2 plots, which leads to an error :

Error: Cannot create zero-length unit vector ("unit" subsetting)

This is the example code:

for (i in Classes)
{
  x <- filter(all_data_R2_filtered, class.x== "i" )
  
  bp <- ggplot(data = x, aes(x=dil, y=mmol, color=AcquiMeth))+
    geom_point()+
    facet_wrap_paginate(name.x ~ ., ncol = 5, nrow = 4, scales = "free")
    number_of_pages <- n_pages(bp)
  
  pdf(paste("class",i,".pdf", sep = ""), paper= 'A4r', w= 297, h= 210)
  
  for(j in 1:number_of_pages){
    print(bp + facet_wrap_paginate(name.x ~ . , ncol = 5,  nrow = 4, page = j))
    }
  dev.off()
}

Is there a fix for this? Thanks a lot in advance for your help

0

There are 0 best solutions below