I have at least 10 plots by ggplot(we can call them plot1, plot2 ....). I can output them into separate pdf files. But I prefer to output them in only one pdf file but several pages. One page, one plot from ggplot.
I tried to list all plots and use ggsave but it can not work. Any idea or script can help? Thank you
See the pdf function for this.
For three plots it would look like this (saving into your working directory with default naming). Run through dev.off line before you can open file.
pdf()
plot1
plot2
plot3
dev.off()
If your plots are already stored in a list named list1:
pdf()
list1
dev.off()
Based on aosmith's answer, here's a simple wrapper function to save lists of ggplot2 plots to a single pdf.
GG_save_pdf = function(list, filename) {
#start pdf
pdf(filename)
#loop
for (p in list) {
print(p)
}
#end pdf
dev.off()
invisible(NULL)
}
Related
I am trying to output a series of the file using the R.
Usually, we can use the following code to output a plot:
jpeg("XXXXX_XXXX.jpg")
ggplot(data=YEAR_ZIP_DATA, aes(x=SOME_VARIABLE)) + geom_bar()
dev.off()
The above code can get me a file in the current working directory called XXXXX_XXXX.jpg
Now I want to write a loop to create a series of file: for each year, draw a bar chart for each zip code and save to the current directory. Here is the code:
# year_list: a list of distinctive years
for(year in year_list){
# zip_list: a list of distinctive zip codes
for(zip in zip_list){
# some code to get a filename like 10010_2018.jpg
filename <- (some code)
# some code to subset the data to get the current zip and year
year_zip_data <- (some code)
jpeg(filename)
ggplot(data=year_zip_data, aes(x=SOME_VARIABLE)) + geom_bar()
dev.off()
}
}
However, after the above loop, there is nothing in the current working directory... How should I solve the problem?
Thanks in advance!
Try ggsave function. It directly saves the graphics object created by ggplot.
My chunk in Sweave:
<<fig=TRUE,echo=FALSE>>=
for(i in 1:10) {
plot(rep(i,10))
dev.new()
}
#
In the resulting pdf I get only one plot (from the first iteration). I would like to have all of the 10 plots printed. What am I doing wrong? I tried replacing dev.new() with frame() and plot.new() but nothing happened.
As #rawr suggests the easiest solution is to switch to knitr (there's really no reason at all not to!) and put fig.keep="all" in your code chunk options (if you switch to knitr you don't need fig=TRUE any more ... including figures works automatically, fig.keep="none" is the analogue of fig=FALSE)
Alternatively, if you want to stick with vanilla Sweave, check the Sweave manual p. 17:
A.9 Creating several figures from one figure chunk does not work
Consider that you want to create several graphs in a loop similar to
<<fig=TRUE>>
for (i in 1:4) plot(rnorm(100)+i)
#
This will currently not work, because Sweave allows only one graph per figure chunk. The simple reason is that Sweave opens a postscript device before executing the code and closes it
afterwards. If you need to plot in a loop, you have to program it along the lines of
<<results=tex,echo=FALSE>>=
for(i in 1:4){
file=paste("myfile", i, ".eps", sep="")
postscript(file=file, paper="special", width=6, height=6)
plot(rnorm(100)+i)
dev.off()
cat("\\includegraphics{", file, "}\n\n", sep="")
}
#
My chunk in Sweave:
<<fig=TRUE,echo=FALSE>>=
for(i in 1:10) {
plot(rep(i,10))
dev.new()
}
#
In the resulting pdf I get only one plot (from the first iteration). I would like to have all of the 10 plots printed. What am I doing wrong? I tried replacing dev.new() with frame() and plot.new() but nothing happened.
As #rawr suggests the easiest solution is to switch to knitr (there's really no reason at all not to!) and put fig.keep="all" in your code chunk options (if you switch to knitr you don't need fig=TRUE any more ... including figures works automatically, fig.keep="none" is the analogue of fig=FALSE)
Alternatively, if you want to stick with vanilla Sweave, check the Sweave manual p. 17:
A.9 Creating several figures from one figure chunk does not work
Consider that you want to create several graphs in a loop similar to
<<fig=TRUE>>
for (i in 1:4) plot(rnorm(100)+i)
#
This will currently not work, because Sweave allows only one graph per figure chunk. The simple reason is that Sweave opens a postscript device before executing the code and closes it
afterwards. If you need to plot in a loop, you have to program it along the lines of
<<results=tex,echo=FALSE>>=
for(i in 1:4){
file=paste("myfile", i, ".eps", sep="")
postscript(file=file, paper="special", width=6, height=6)
plot(rnorm(100)+i)
dev.off()
cat("\\includegraphics{", file, "}\n\n", sep="")
}
#
Having an unusual problem with creating multiple files in R with ggplot2.
I've got multiple plots to create for multiple people, so I'm creating all the plots for each person in a pdf. So it goes something like this...
for(i in 1:10)
{
pdf(paste("person",i,".pdf",sep=""))
ggplot2(...)+.........
ggplot2(...)+.........
ggplot2(...)+.........
ggplot2(...)+.........
dev.off()
}
I've verified that all the code to create the plots is working and that creating a single pdf works, no problems there. The problem arises when I try to run the loop, it creates the files, but they're blank. I've tried everything I can think of and can't seem to find any information about this. I've tried in RStudio (Windows) and command line (ubuntu), both create the same issue.
Any insight or an alternative would be appreciated, thanks
You need to use print for each plot want you output into a pdf.
library(ggplot2)
dat = data.frame(x1=rnorm(10), x2=rnorm(10))
for(i in 1:2){
pdf(paste("person",i,".pdf",sep=""))
p1 = ggplot(dat, aes(x=x1)) + geom_histogram()
p2 = ggplot(dat, aes(x=x2)) + geom_histogram()
print(p1)
print(p2)
dev.off()
}
I want to loop over a plot and put the result of the plot in a PDF.
The following code is used to do this:
What this does is loop 3 times and plot 3 different plots from the iris dataset. Then it should save it to the C:/ drive. The PDF files are created, but are corrupted.
for(i in 1:3){
pdf(paste("c:/", i, ".pdf", sep=""))
plot(cbind(iris[1], iris[i]))
dev.off()
}
To drawn lattice plots on the device, one needs to print the object produced by a call to one of the lattice graphics functions. Normally, in interactive use, R auto prints objects if not assigned. In loops however, auto printing does not work, so one must arrange for the object to be printed, usually by wrapping it in print().
Here is an example (please excuse my abuse of the formula notation ;-):
require(lattice)
for(i in 1:3) {
pdf(paste("plot", i, ".pdf", sep = ""))
print(xyplot(iris[,1] ~ iris[,i], data = iris))
dev.off()
}
This produces the three plots on a pdf device.
Is a file name that contains "c:/" a valid file name on your OS? That looks like part of the working directory that you'd want to set before calling pdf. I get an error telling me it can't open that file:
Error in pdf(paste("c:/", i, ".pdf", sep = "")) :
cannot open file 'c:/1.pdf'
If I drop the "c:/" bit from the file name, three PDFs are generated properly. Also, if you move the dev.off() outside of the for loop, you'll get a single PDF with three pages instead of three PDFs. May or may not be what you want...
for(i in 1:3){
pdf(paste("plot", i,".pdf",sep=""))
plot(cbind(iris[1],iris[i]))
dev.off()
}