I have multiple plots to save as .pdf
files and they are created in R by using par(mfrow=c(1,2))
, ie per each figure (to be saved) there are 2 plots disposed by 1 row and 2 columns.
Since my total number of plots is quite high I am creating the plots with a for loop.
How can I save the figures (with 2 plots each one) as pdf files in the for loop?
Here's same funky code:
## create data.frames
df_1 = data.frame(x = c(1:100), y = rnorm(100))
df_2 = data.frame(x = c(1:100), y = rnorm(100))
df_3 = data.frame(x = c(1:100), y = rnorm(100))
df_4 = data.frame(x = c(1:100), y = rnorm(100))
## create list of data.frames
df_lst = list(df_1, df_2, df_3, df_4)
## plot in for loop by 1 row and 2 cols
par(mar=c(3,3,1,0), mfrow=c(1,2))
for (i in 1:length(df_lst)) {
barplot(df_lst[[i]]$y)
}
Let's say I want to save the plots with the pdf
function. Here's what I tried:
for (i in 1:length(df_lst)) {
pdf(paste('my/directory/file_Name_', i, '.pdf', sep = ''), height = 6, width = 12)
barplot(df_lst[[i]]$y)
dev.off()
}
My solution is clearly wrong because the pdf
function saves a figure at each loop (ie 4 instead of 2).
Any suggestion? Thanks
Sounds like you could use a nested loop here: an outer loop for each file you create, and an inner loop for each multi-panel figure you create. Since all the data frames are stored in a 1-d list, you'll then need to keep track of the index of the list that you are plotting.
Here's one way to do that:
nrow <- 1
ncol <- 2
n_panels <- nrow * ncol
n_files <- length(df_lst) / n_panels
for (i in seq_len(n_files)) {
file <- paste0("file_", i, ".pdf")
pdf(file, height = 6, width = 12)
# plot params need to be set for each device
par(mar = c(3, 3, 1, 0), mfrow = c(nrow, ncol))
for (j in seq_len(n_panels)) {
idx <- (i - 1) * n_panels + j
barplot(df_lst[[idx]]$y)
}
# updated to also add a legend
legend("bottom", legend = "Bar", fill = "grey")
dev.off()
}
If you just want one file with multiple pages, all you need to do is move the pdf()
call outside your original loop, and move the parameter setting after the pdf()
:
pdf('my/directory/file_Name.pdf', height = 6, width = 12)
par(mar=c(3,3,1,0), mfrow=c(1,2))
for (i in 1:length(df_lst)) {
barplot(df_lst[[i]]$y)
}
dev.off()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.