Output multiple plots to a single pdf in for loop - r

I am having trouble generating a pdf with multiple plots. When I arrange my plots in a for loop it seems it looses the connection to the pdf and produces an empty pdf.
I have a list of lists called p, with p.length(p) ==2.
p[[1]] and p[[2]] contain ggplots.
########## This works ##########
myPDFPath = "output/countryProfilesIndividual_testI.pdf"
pdf(file=myPDFPath, onefile = TRUE)
gridExtra::marrangeGrob(p[[1]], nrow = length(p[[1]]), ncol = 1, top=quote("My Quote"))
gridExtra::marrangeGrob(p[[2]], nrow = length(p[[2]]), ncol = 1, top=quote("My Quote"))
dev.off()
--> Here I get two pages with plots as expected.
########## This works NOT ##########
myPDFPath = "output/countryProfiles.pdf"
pdf(file=myPDFPath, onefile = TRUE)
for (listIdx in 1:length(p))
{
gridExtra::marrangeGrob(p[[listIdx]], nrow = length(p[[listIdx]]), ncol = 1, top=quote("MyQuote"))
}
dev.off()
--> The file is written, but it is empty
Do curly brackets cause some behaviour that I am not aware of?
Please note, I don't want to create individual pdfs, but bring everything in one pdf together.
I want to arrange the plots dynamically, so all lapply possibilities I found don't help me because e.g. the nrow or top parameters have to be set individually.

Related

Print several plots on one PDF page in R

I am trying to plot 4 graphs on one single PDF page. Untill now, the only output I got was 1 file per page. I would like to have all of them on one page. One plot is stocked in "c", the three others are produced using a loop. Here is the code I use :
pdf("path_to_file.pdf", onefile = TRUE)
plot(c)
for (exp in expL) {
plot(plot_list[[exp]])
}
dev.off
I tried without the "onefile" specification, or adding :
par(mfrow=c(2,2))
or even
layout(matrix(c(1,2,3,4), ncol = 2, byrow = TRUE))
but nothing helps...
I would be grateful for some help.
Thank you very much!
c should be same type of plot as expL.
If they are, do:
library(cowplot)
plot_grid( append( list(c), expL ), nrow=2 )

Plot ggplots stored in list over several pages

I know similar questions have been already asked so sorry if this is a redundant question! However, I can't seem to find a solution that arranges several ggplots from a list onto 1 page over several pages.
I have a list of approximately 100 ggplots - I want to plot every 4 ggplots on 1 page, and iterate through the list until all the ggplots have been plotted. I then want to export the approximately 25 pages to a single pdf file.
So far, I've tried:
pdf("plots.pdf", onefile = TRUE, width = 11, height = 8.5)
for (i in 0:24) {
ggarrange(list[[4i+1]], list[[4i+2]], list[[4i+3]], list[[4i+4]],
nrow = 2, ncol = 2, common.legend = TRUE, legend = 'bottom'
}
dev.off()
However, I'm getting the error that the subscript is out of bounds. I've tried narrowing the range in the for loop to try to overcome this error but it's returning the same error. I also know we can use marrangeGrob(), but I can't seem to add a common legend to the file.
Really appreciate any help!
It would be helpful if you could provide some small list of plots to test on.
I have tried to recreate your scenario, and have found that it wasn't working unless I explicitly print the ggarrange object.
plot <- ggplot(mtcars, aes(x = cyl, y = mpg)) +
geom_point()
plot_list <- list(plot, plot, plot, plot, plot, plot, plot, plot)
pdf("test.pdf", 11, 8.5)
for(i in 0:3){
print(ggarrange(plot_list[[2*i + 1]], plot_list[[2*i + 1]], nrow = 2, ncol = 1))
}
dev.off()
This worked for me. Noting akrun's comment that you forgot your * symbol.

Save automatically produced plots in R

I'm using a function in R able to analyse my data and produce several plots.
The function is "snpzip" from adegenet package.
I would like to save automatically the three plots that the function produces as part of the output. Do you have any suggestion on how to do it?
I want to point to the fact that I know how to save a single plot, for instance with png or pdf followed by dev.off(). My problem is that when I run snpzip(snps, phen, method = "centroid"), the outcomes are three plots (which I would like to save).
I report here the same example as in the "adegenet" package:
simpop <- glSim(100, 10000, n.snp.struc = 10, grp.size = c(0.3,0.7),
LD = FALSE, alpha = 0.4, k = 4)
snps <- as.matrix(simpop)
phen <- simpop#pop
outcome <- snpzip(snps, phen, method = "centroid")
If you use a filename with a C integer format in it, then R will substitute the page number for that part of the name, generating multiple files. For example,
png("page%d.png")
plot(1)
plot(2)
plot(3)
dev.off()
will generate 3 files, page1.png, page2.png, and page3.png. For pdf(), you also need onefile=FALSE:
pdf("page%d.pdf", onefile = FALSE)
plot(1)
plot(2)
plot(3)
dev.off()

Saving ggplot graphs to pdf not formatting correctly in PDF

This is a follow on question to my original here
I am currently trying to save the outputs of a ggplot graph to .pdf but I am running into some problems.
I run the following on the dput data on the original question (I repaste everything below).
library(gridExtra)
pdf("Plots.pdf", onefile = TRUE)
for(j in 1:length(plotList)) {
grid.arrange(plotList[[j]], nrow = 2)
}
dev.off()
This saves the files as a pdf document but instead of getting two graphs per page I get one graph which takes up half a page. Is it possible to resize the graphs, when I select nrow = 3 I get the same problem, I get one graph in the top 3rd / half of the page and a blank space for the rest. I provide a screen shot of the output:
Here is a minimal example:
# Make empty list for plots
plotList <- list()
# Build plots
library(ggplot2)
for(i in 1:2){
plotList[[i]] <-
ggplot(mtcars, aes(mpg, cyl)) +
geom_point() +
labs(title = i)
}
# Save plots
library(gridExtra)
pdf("Plots.pdf", onefile = TRUE)
for(j in 1:length(plotList)) {
grid.arrange(plotList[[j]], nrow = 2)
}
dev.off()
Credit to #LachlanO
You problem comes from how you are calling grid.arrange. By including it in a loop, you are telling it to create multiple separate plots, like this:
grid.arrange(plotList[[1]], nrow = 2)
grid.arrange(plotList[[2]], nrow = 2)
grid.arrange(plotList[[3]], nrow = 2)
What you actually are trying to do is create one grid.arrange object which contains all the plots. To do this, you need call the function against the list:
do.call("grid.arrange", c(plotList, nrow=2))
Alternatively, you can use the cowplot package and use:
cowplot::plot_grid(plotlist = plotList, nrow = 2)
So to save the PDF you can use:
pdf("Plots.pdf", onefile = TRUE)
do.call("grid.arrange", c(plotList, nrow=2))
dev.off()

R: Print ggplots and matrices to panels in PDF?

I'm creating a multipage PDF, where each page should contain 2 graphs (ggplot2) and 2 matrices. Previously, I was using plot(), where the code and PDF layout for each page was something like this:
pdf("Rplots.pdf", paper = "letter", width = 7.5, height = 10)
layout(matrix(c(1,1,2,4,3,3),3,2, byrow = TRUE), heights = c(7,4,7))
# Plot at the top of each page
plot(dataTop)
# Summary at the bottom of each page
summary <- matrix(dataTop, ncol = 2, nrow = 6)
textplot(summary)
# Plot at the top of each page
plot(dataBottom)
# Summary at the bottom of each page
summary <- matrix(dataBottom, ncol = 2, nrow = 6)
textplot(summary)
dev.off()
I've replaced the plot() with ggplot() and have trouble getting it to print using the same panel layout.
1) Is there any simple way to print a combination of ggplots and matrices using the type of layout I have above?
2) Is there some way to ensure the ggplot is confined/expanded to some certain amount of space on the PDF?
Thank you!

Resources