R: Save multiple plots from a file list into a single file (png or pdf or other format)
Here a fast method to aggregate many png files:
- read your png using
readPNG
- convert them to a raster , and plot them using
grid.raster
: very efficient.
Something like this :
library(png)
library(grid)
pdf('somefile1.pdf')
lapply(ll <- list.files(patt='.*[.]png'),function(x){
img <- as.raster(readPNG(x))
grid.newpage()
grid.raster(img, interpolate = FALSE)
})
dev.off()
Edit : loading png , arranging them and merge them in the same pdf :
First you should store your png files in a list of grobs using rasterGrob
:
plots <- lapply(ll <- list.files(patt='.*[.]png'),function(x){
img <- as.raster(readPNG(x))
rasterGrob(img, interpolate = FALSE)
})
Then save them using the excellent handy function marrangeGrob
:
library(ggplot2)
library(gridExtra)
ggsave("multipage.pdf", marrangeGrob(grobs=plots, nrow=2, ncol=2))
Save/export plots from list of plots as single .png files
we can use:
sapply(1:length(list_plots), function(i) ggsave(
filename = paste0("plots ",i,".pdf"),
plot = list_plots[[i]],
width = 15, height = 9
))
For names: see https://stackoverflow.com/a/73370416/5224236
mynames <- sapply(names(tbls), function(x) {
paste("How do they rank? -",gsub("\\.",": ",x))
})
myfilenames <- names(tbls)
plot_likert <- function(x, myname, myfilename){
p <- plot(likert(x),
type ="bar",center=3,
group.order=names(x))+
labs(x = "Theme", subtitle=paste("Number of observations:",nrow(x)))+
guides(fill=guide_legend("Rank"))+
ggtitle(myname)
p
}
list_plots <- lapply(1:length(tbls),function(i) {
plot_likert(tbls[[i]], mynames[i], myfilenames[i])
})
R Generate Multiple Plots for a single pdf
Based on the OP wanting 4 plots per PDF page, I would recommend:
pdf('plots.pdf')
par(mfrow=c(2,2))
for (i in 1:length(categories){
category_data <- data[which(data$category==categories[i]),]
plot(category_data$y,category_data$x)}
dev.off()
If the OP decides to plot a different number of graphs per page, the mfrow
parameter can be changed. Currently it is set for 2 rows x 2 columns = 4 plots per page.
R: Save multiple svg/png/tif plots
If you look at the help pages ?png
and ?svg
you will see that the default file names are "Rplot%03d.png"
and "Rplot%03d.svg"
respectively. The %03d
part of those names means that each time a new plot is created it will automatically open a new file and that part of the file name will be replaced by an incrementing integer. So the first file will be "Rplot001.png" and the next will be "Rplot002.png" etc.
If you don't like the default file name you can create your own and still insert the portion to be replaced by an integer, such as "myplots%02d.png"
. The %
says this is where the number part starts, the 0
is optional, but says to 0 pad the numbers (so you get 01, 02, ... rather than 1, 2, ...), this is generally preferred so that the sorting works out correctly (otherwise you may see the sorting as 1,10,11,2,3,...) and the digit (3 in the default, 2 in my example) is the number of digits, if you will create more than 1,000 plots you should up that to 4, if you know that you will not create 100 then 2 is fine (1 is fine if you know that you will produce fewer than 10). And the d
is just an indicator for an integer.
combine png files in current folder to a single png file in r
the list of parameters for marrangeGrob
has changed recently; there is no need for do.call
any longer, just use the grobs
argument,
ggsave("Plots_Combined.pdf",width=8.5, height=11,
marrangeGrob(grobs = plots, nrow=2, ncol=1,top=NULL))
for png, you can't output multiple pages to a single file, but this trick could help,
ggsave("Plots_Combined%03d.png",width=8.5, height=11,
marrangeGrob(grobs = plots, nrow=2, ncol=1,top=NULL))
Saving multiple ggplots from ls into one and separate files in R
It's best to have your plots in a list
l = mget(plots)
Then you can simply print them page-by-page,
pdf("all.pdf")
invisible(lapply(l, print))
dev.off()
or save one plot per file,
invisible(mapply(ggsave, file=paste0("plot-", names(l), ".pdf"), plot=l))
or arrange them all in one page,
# On Windows, need to specify device
ggsave("arrange.pdf", arrangeGrob(grobs = l), device = "pdf")
or arrange them 2x2 in multiple pages,
# need to specify device on Windows
ggsave("arrange2x2.pdf", marrangeGrob(grobs = l, nrow=2, ncol=2),
device = "pdf")
etc.
(untested)
RScript: how to get the plots saved into multiple files (say png) rather than saved into the Rplots.pdf?
To save your plots as a png
file, the general idea is:
png("spam.png")
plot(...)
dev.off()
similar functions are jpeg
and tiff
. Wrap all your plots in such calls to png
to save the plots to specific names. Adding png()
at the top of the script will save all plots in different png files: Rplot001.png
, Rplot002.png
. I would however try and give meaningful names to the plots.
Using Cairo devices, you can use savePlot
. When you plot with ggplot2
, the best way imo to save a plot is using ggsave
.
Export R plot to multiple formats
Without using ggplot2
and other packages, here are two alternative solutions.
Create a function generating a plot with specified device and
sapply
it# Create pseudo-data
x <- 1:10
y <- x + rnorm(10)
# Create the function plotting with specified device
plot_in_dev <- function(device) {
do.call(
device,
args = list(paste("plot", device, sep = ".")) # You may change your filename
)
plot(x, y) # Your plotting code here
dev.off()
}
wanted_devices <- c("png", "pdf", "svg")
sapply(wanted_devices, plot_in_dev)Use the built-in function
dev.copy
# With the same pseudo-data
# Plot on the screen first
plot(x, y)
# Loop over all devices and copy the plot there
for (device in wanted_devices) {
dev.copy(
eval(parse(text = device)),
paste("plot", device, sep = ".") # You may change your filename
)
dev.off()
}
The second method may be a little tricky because it requires non-standard evaluation. Yet it works as well. Both methods work on other plotting systems including ggplot2
simply by substituting the plot-generating codes for the plot(x, y)
above - you probably need to print
the ggplot object explicitly though.
Save all plots already present in the panel of Rstudio
In RStudio, every session has a temporary directory that can be obtained using tempdir()
. Inside that temporary directory, there is another directory that always starts with "rs-graphics"
and contains all the plots saved as ".png"
files. Therefore, to get the list of ".png"
files you can do the following:
plots.dir.path <- list.files(tempdir(), pattern="rs-graphics", full.names = TRUE);
plots.png.paths <- list.files(plots.dir.path, pattern=".png", full.names = TRUE)
Now, you can copy these files to your desired directory, as follows:
file.copy(from=plots.png.paths, to="path_to_your_dir")
Additional feature:
As you will notice, the .png
file names are automatically generated (e.g., 0078cb77-02f2-4a16-bf02-0c5c6d8cc8d8.png
). So if you want to number the .png
files according to their plotting order in RStudio, you may do so as follows:
plots.png.detials <- file.info(plots.png.paths)
plots.png.detials <- plots.png.detials[order(plots.png.detials$mtime),]
sorted.png.names <- gsub(plots.dir.path, "path_to_your_dir", row.names(plots.png.detials), fixed=TRUE)
numbered.png.names <- paste0("path_to_your_dir/", 1:length(sorted.png.names), ".png")
# Rename all the .png files as: 1.png, 2.png, 3.png, and so on.
file.rename(from=sorted.png.names, to=numbered.png.names)
Hope it helps.
save plots made by loop in a file
In the code you had shared:
for(i in 1:28) {
plot_i <- ggplot(Num, aes(Num[,i]))+ geom_histogram(fill="skyblue", col="Blue")+
ggtitle(names(Num)[i])+theme_classic()
ggplot2::ggsave(filename = paste0("plot_",i,".png"),plot_i, path = "E:/Folder1")
}
You are storing the plot object in the variable plot_i
. You are not printing those plots. You need to insert, print(plot_i)
statement before saving the plot using ggplot
as follows:
for(i in 1:28) {
plot_i <- ggplot(Num, aes(Num[,i]))+ geom_histogram(fill="skyblue", col="Blue")+
ggtitle(names(Num)[i])+theme_classic()
print(plot_i)
ggplot2::ggsave(filename = paste0("plot_",i,".png"),plot_i, path = "E:/Folder1")
}
The reason why you need to print is because, ggsave
defaults to save the last displayed plot, and by printing you actually display on the Rs display devices. In simpler words this is what ggsave
does:
png('file_name.png') #it opens a graphics devices, can be other also like jpeg
print(plot_i) #displays the plot on graphics device
dev.off() #closes the graphic device
Related Topics
How to Replace Numeric Codes with Value Labels from a Lookup Table
Subset Observations That Differ by at Least 30 Minutes Time
Generating a Heatmap That Depicts the Clusters in a Dataset Using Hierarchical Clustering in R
Check If R Package Is Installed Then Load Library
Sine Curve Fit Using Lm and Nls in R
A^K for Matrix Multiplication in R
Using Mean with .Sd and .Sdcols in Data.Table
Convert Lat/Lon to Zipcode/Neighborhood Name
Set Upper Limit in Ggplot to Include Label Greater Than the Maximum Value
How to Make Discrete Gradient Color Bar with Geom_Contour_Filled
Finding Elements of Lists in R
Using Filtered Datatables in Shiny
Extracting Coefficients and Their Standard Error for Each Unit in an Lme Model Fit