Search code examples
rggplot2facet-wrapggforce

GGplot multiple pages prints same first plots over and over


I'm trying to make a pdf of multiple plots, but the pdf only ever prints the first n amount of plots. I'm using ggforce::facet_wrap_paginate. Below is the code I've written. I'd love if anyone had any advice for why I'm only getting the first 6 plots? I've tried this using PNG as well, but I had the same issue. When it's done, I'm expecting a pdf of somewhere between 20-30 pages (about 160 plots). So you can understand my frustration with only 6 plots...

pg <- ceiling(
  length(levels(Tidy$Region)) / 6
)

pdf("attempt3001.pdf")
for(i in seq_len(pg)){
  print(ggplot(Tidy, aes(x=Year, y=Value / 1000, group=Country, color=Status))+
      geom_line()+
      theme_classic()+
      facet_wrap_paginate(~Region, nrow = 3, ncol = 2, page = 1, scales = "free"))
}
dev.off()

I have seen similar questions on stack, but they were before the advent of facet_wrap_paginate (which is amazing!) or didn't solve my issue. Many thanks in advance.

This question is the one I modeled my current code off of. I wish I could comment on that one, but I've got no reputation haha.


Solution

  • The problem was simply that you didn't draw each page i but only the first one. Replace page = 1 by page = i in your code.

    pg <- ceiling(
     length(levels(Tidy$Region)) / 6
    )
    
    pdf("attempt3001.pdf")
    for(i in seq_len(pg)){
      print(ggplot(Tidy, aes(x=Year, y=Value / 1000, group=Country, color=Status)) +
             geom_line() +
             theme_classic() +
             facet_wrap_paginate(~Region, nrow = 3, ncol = 2, page = i, scales = "free"))
    }
    dev.off()