From a list of base R plots, create a multipage pdf with multiple plots per page - r

I am trying to create a multipage pdf with multiple plots per page from a list of plots created using base R plot() function. I know this is easy if the plots are created using ggplot2, but the plots I have come from a package that uses base R plot(). I store the plots in a list and then want to create a pdf from the list of plots. The following section of code gives a working example of what I am after:
# This creates 1 file with multiple pages & each page having 4 plots
pdf(file = if(TRUE) "Rplot.pdf" else "Rplot%03d.pdf",
paper = "letter")
par(mfrow=c(nrow = 2, ncol = 2))
for (i in 1:6){
x=rnorm(5)
y=rnorm(5)
plot(x,y)
title(paste0("Plot ",i))
}
I am trying to obtain the same result when the plots are stored in a list, as in the following:
# Create plots and store in a list
listofplots <- list()
for (i in 1:6){
x=rnorm(5)
y=rnorm(5)
plot(x,y)
title(paste0("Plot ",i))
listofplots[[i]] <- recordPlot()
}
# Create pdf
pdf(file = "Rplot.pdf")
par(mfrow=c(nrow = 2, ncol = 2))
for(i in 1:6) {
print(listofplots[[i]])
}
dev.off()
The above code generates 1 file, with 1 plot per page, rather than multiple plots per page. Clearly I am missing something simple.

Related

Saving S3 aggr object in a way mice_plots can be visualized by ggplot in a grid arrangement

I am using a for loop to loop through a dataset and produce a mice_plot per category. In the for loop, I would like to save the produced mice_plot so that I can later plot them all in a grid.
my code looks like this atm:
for center in unique(df$center){
dispatch_centers <- list()
mice_plot <- aggr(center, ...)
# save mice_plot some how in a way I can later open it with ggplot
as.grob()?
#add to list
center_plots[[center]] <- mice_plot
}
grid.arrange(grobs = center_plots, ncol = 2)
However, I do not understand the aggr() object nor how to save it so I can later handle it with ggplot2. Does anyone have any ideas?

Save plots generated within a loop in R

I am looking for a way to save ggplots and flextables to the workspace and later combine these objects that were generated within a loop.
Here is a simple example:
for (i in 1:3) {x<-rnorm(20, 5, 5-i); hist(x)}
In this example, x is overwritten every time and a new histogram is generated. I would want to store each histogram that is generated within the loop in the current workspace and later combine those histograms in one plot (without having to actually save each one of them). How can I go about that best?
Thanks a lot in advance!
We could set the par and get the plots into a single page
par(mfrow = c(3, 1))
for (i in 1:3) {
x<-rnorm(20, 5, 5-i)
hist(x)
}
If we want to store the plots and print, then create a NULL list to store the objects, and then do the plotting later
p1 <- vector('list', 3)
for(i in seq_along(p1)) {
x<- rnorm(20, 5, 5-i)
p1[[i]] <- hist(x)
}
par(mfrow = c(3, 1))
for(p in p1) plot(p)

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()

Plot multiple ggplot2 on same page

I have a working loop which generates and can save individual plots from each file saved in a directory.
I want to plot all of the returned plots in a single file as a 2x2 grid over multiple pages but cannot do this.
I have tried to save the plot objects in a list
pltList <- list()
pltList[]
for (f in 1:length(files)){
plot_object <- ggplot2(...) #make ggplot2 plot
print(plot_object)
pltList[[f]] <- plot_object #save ggplot2 plot in list
}
jpeg(filename.jpg)
par(mfrow=c(2,2)) #to generate 2x2 plot per page
print(pltList[[1]])
print(pltList[[2]])
...
print(pltList[[f]])
dev.off()
The problem is that the resulting saved .jpg file only contains the last plot and not a 2x2 grid of all plots over many pages which is what I want.
EDIT
My first problem is how to save each plot from the loop in the list - how can I view the saved objects from the list to make sure they have been saved correctly?
When I do print(pltList[1]), the resulting output is:
function (x, y, ...)
UseMethod("plot")
<bytecode: 0x0000000010f43b78>
<environment: namespace:graphics>
rather than the actual plot. It seems that the plots are not being saved in the list as expected. How can I correct for this?
Hopefully, once this is fixed, your plotting suggestions will work.
I did recently the same. I used grid.arrange().
library(ggplot2)
library(gridExtra)
library(grid)
p1<-ggplot()+geom_line(aes(x=1:10,y=1:10))
p2<-ggplot()+geom_line(aes(x=1:10,y=1:10))
p3<-ggplot()+geom_line(aes(x=1:10,y=1:10))
p4<-ggplot()+geom_line(aes(x=1:10,y=1:10))
grid.arrange(p1,p2,p3,p4, ncol=1, top=textGrob("Multiple Plots", gp=gpar(fontsize=12, font = 2)))
Assuming you need a PDF output where every page has multiple plots plotted as one, e.g.: if there are 12 plots then 4 plots per page.
Try this example:
library(ggplot2)
library(cowplot)
# list of 12 dummy plots, only title is changing.
pltList <- lapply(1:12, function(i){
ggplot(mtcars,aes(mpg,cyl)) +
geom_point() +
ggtitle(paste("Title",i))})
# outputs 3 jpeg files with 4 plots each.
for(i in seq(1,12,4))
ggsave(paste0("Temp",i,".jpeg"),
plot_grid(pltList[[i]],
pltList[[i+1]],
pltList[[i+2]],
pltList[[i+3]],nrow = 2))
# or we can output into 1 PDF with 3 pages using print
pdf("TempPDF.pdf")
for(i in seq(1,12,4))
print(plot_grid(pltList[[i]],
pltList[[i+1]],
pltList[[i+2]],
pltList[[i+3]],nrow = 2))
dev.off()
EDIT:
Another way using gridExtra, as suggested by #user20650:
library(gridExtra)
#output as PDF
pdf("multipage.pdf")
#use gridExtra to put plots together
marrangeGrob(pltList, nrow=2, ncol=2)
dev.off()

putting multiple plots on one pdf in r

I am outputting plots as png based on grouping according to the dataframe vector called "chr". This generates lots of plots but I would like to have them all in one png. I am using the plot function in r rather than ggplot2.
My code so far:
for(jj in ind){
png(paste("/Users/sebastianzeki/Desktop/SequencingScripts/Plots/",jj,".png"))
indic = which(ret$chr == jj)
plot(ret$binRight[indic],ret$SummedZScore[indic],pch=19,xlab="Locus",ylab="Summed ZScore",type="h",lwd=20, space=0)
dev.off()
How can I get all the plots on one png (or pdf if thats easier)?
Suppose length(ind) = 10
png(paste("/Users/sebastianzeki/Desktop/SequencingScripts/Plots/",jj,".png"))
par(mfrow=c(5,2))
for(jj in ind){
indic = which(ret$chr == jj)
plot(ret$binRight[indic],ret$SummedZScore[indic],pch=19,xlab="Locus",ylab="Summed ZScore",type="h",lwd=20, space=0)
}
dev.off()
This can make one png file or if you want to make a pdf file
How to print R graphics to multiple pages of a PDF and multiple PDFs?
Look at the above thread for help.
A simple example :
png("temp.png", width = 600, height = 2000)
par(mfrow=c(8,3), mar = rep(0.5, 4), oma = rep(0.5, 4))
for (i in 1:24) {
hist(runif(20), main = NULL)
}
dev.off()

Resources