Prevent foremost blank page when plotting to PDF in R (with survminer)

When I was generating a a series of plots using package “survminer” in R, I often suffer from a blank page generated automatically at foremost of the PDF. For example:

library(survival)
library(survminer)

# Using lung dataset.

cairo_pdf(filename = "./temp_plot.pdf", onefile = TRUE)
for (single_sex in unique(lung$sex)) {
    lung_single_sex = subset(lung, sex == single_sex)
    cox_result = coxph(Surv(time, status) ~ age + ph.ecog, data = lung_single_sex)
    print(ggforest(cox_result, data = lung_single_sex))
}
dev.off()

Then there will be three pages in temp_plot.pdf and the first page will be blank.

I don’t know the exact reason of the issue. But it seems ggforest() called ggpubr::as_ggplot(), which called gridExtra:::grid.newpage() or something similar, then caused the blank page before the plot. I searched the issue on the web and most people advised setting onefile = FALSE in cairo_pdf() to prevent the blank page. While it is not an ideal workaround because it makes the PDF contain only the last plot written to the file.

After some attempts, I found a relatively better workaround. The key is the plot(s) must be generated BEFORE (but not after) the PDF device opened. We can use a list to store the plot(s) which will be plotted on the PDF. For example:

p_list = list() # To store the plots.
for (single_sex in unique(lung$sex)) {
    lung_single_sex = subset(lung, sex == single_sex)
    cox_result = coxph(Surv(time, status) ~ age + ph.ecog, data = lung_single_sex)
    p = ggforest(cox_result, data = lung_single_sex)
    p_list = c(p_list, list(p))
}
cairo_pdf(filename = "./temp_plot.pdf", onefile = TRUE)
for (p in p_list) {
    print(p)
}
dev.off()

Then the pages of PDF seem normal.

References:

https://github.com/hms-dbmi/UpSetR/issues/90

https://github.com/wilkelab/cowplot/issues/24

https://blog.csdn.net/weixin_34032827/article/details/85900976