Saving multiple plots in a single PDF in R [duplicate] - r

I know that
pdf("myOut.pdf")
will print to a PDF in R. What if I want to
Make a loop that prints subsequent graphs on new pages of a PDF file (appending to the end)?
Make a loop that prints subsequent graphs to new PDF files (one graph per file)?

Did you look at help(pdf) ?
Usage:
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot%03d.pdf"),
width, height, onefile, family, title, fonts, version,
paper, encoding, bg, fg, pointsize, pagecentre, colormodel,
useDingbats, useKerning)
Arguments:
file: a character string giving the name of the file. For use with
'onefile=FALSE' give a C integer format such as
'"Rplot%03d.pdf"' (the default in that case). (See
'postscript' for further details.)
For 1), you keep onefile at the default value of TRUE. Several plots go into the same file.
For 2), you set onefile to FALSE and choose a filename with the C integer format and R will create a set of files.

Not sure I understand.
Appending to same file (one plot per page):
pdf("myOut.pdf")
for (i in 1:10){
plot(...)
}
dev.off()
New file for each loop:
for (i in 1:10){
pdf(paste("myOut",i,".pdf",sep=""))
plot(...)
dev.off()
}

pdf(file = "Location_where_you_want_the_file/name_of_file.pdf", title="if you want any")
plot() # Or other graphics you want to have printed in your pdf
dev.off()
You can plot as many things as you want in the pdf, the plots will be added to the pdf in different pages.
dev.off() closes the connection to the file and the pdf will be created and you will se something like
> dev.off()
null device 1

Related

R program: Plots not showing up in png file [duplicate]

I plot a simple linear regression using R.
I would like to save that image as PNG or JPEG, is it possible to do it automatically? (via code)
There are two different questions: First, I am already looking at the plot on my monitor and I would like to save it as is. Second, I have not yet generated the plot, but I would like to directly save it to disk when I execute my plotting code.
There are two closely-related questions, and an answer for each.
1. An image will be generated in future in my script, how do I save it to disk?
To save a plot, you need to do the following:
Open a device, using png(), bmp(), pdf() or similar
Plot your model
Close the device using dev.off()
Some example code for saving the plot to a png file:
fit <- lm(some ~ model)
png(filename="your/file/location/name.png")
plot(fit)
dev.off()
This is described in the (combined) help page for the graphical formats ?png, ?bmp, ?jpeg and ?tiff as well as in the separate help page for ?pdf.
Note however that the image might look different on disk to the same plot directly plotted to your screen, for example if you have resized the on-screen window.
Note that if your plot is made by either lattice or ggplot2 you have to explicitly print the plot. See this answer that explains this in more detail and also links to the R FAQ: ggplot's qplot does not execute on sourcing
2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.
dev.print(pdf, 'filename.pdf')
This should copy the image perfectly, respecting any resizing you have done to the interactive window. You can, as in the first part of this answer, replace pdf with other filetypes such as png.
If you want to keep seeing the plot in R, another option is to use dev.copy:
X11 ()
plot (x,y)
dev.copy(jpeg,filename="plot.jpg");
dev.off ();
If you reach a clutter of too many plot windows in R, use graphics.off() to close all of the plot windows.
If you use ggplot2 the preferred way of saving is to use ggsave. First you have to plot, after creating the plot you call ggsave:
ggplot(...)
ggsave("plot.png")
The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to ggsave, notably width, height, and dpi.
Like this
png('filename.png')
# make plot
dev.off()
or this
# sometimes plots do better in vector graphics
svg('filename.svg')
# make plot
dev.off()
or this
pdf('filename.pdf')
# make plot
dev.off()
And probably others too. They're all listed together in the help pages.
For the first question, I find dev.print to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk
dev.print(pdf, file="filename.pdf");
You can replace pdf with other formats such as png.
This will copy the image exactly as you see it on screen. The problem with dev.copy is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.
For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands
pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor
If you use R Studio http://rstudio.org/ there is a special menu to save you plot as any format you like and at any resolution you choose
If you open a device using png(), bmp(), pdf() etc. as suggested by Andrie (the best answer), the windows with plots will not pop up open, just *.png, *bmp or *.pdf files will be created. This is convenient in massive calculations, since R can handle only limited number of graphic windows.
However, if you want to see the plots and also have them saved, call savePlot(filename, type) after the plots are drawn and the window containing them is active.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:
R < myscript.R --no-save
This could be converted to jpg/png as necessary
In some cases one wants to both save and print a base r plot. I spent a bit of time and came up with this utility function:
x = 1:10
basesave = function(expr, filename, print=T) {
#extension
exten = stringr::str_match(filename, "\\.(\\w+)$")[, 2]
switch(exten,
png = {
png(filename)
eval(expr, envir = parent.frame())
dev.off()
},
{stop("filetype not recognized")})
#print?
if (print) eval(expr, envir = parent.frame())
invisible(NULL)
}
#plots, but doesn't save
plot(x)
#saves, but doesn't plot
png("test.png")
plot(x)
dev.off()
#both
basesave(quote(plot(x)), "test.png")
#works with pipe too
quote(plot(x)) %>% basesave("test.png")
Note that one must use quote, otherwise the plot(x) call is run in the global environment and NULL gets passed to basesave().
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()

How to save a plot in .png format in R [duplicate]

I plot a simple linear regression using R.
I would like to save that image as PNG or JPEG, is it possible to do it automatically? (via code)
There are two different questions: First, I am already looking at the plot on my monitor and I would like to save it as is. Second, I have not yet generated the plot, but I would like to directly save it to disk when I execute my plotting code.
There are two closely-related questions, and an answer for each.
1. An image will be generated in future in my script, how do I save it to disk?
To save a plot, you need to do the following:
Open a device, using png(), bmp(), pdf() or similar
Plot your model
Close the device using dev.off()
Some example code for saving the plot to a png file:
fit <- lm(some ~ model)
png(filename="your/file/location/name.png")
plot(fit)
dev.off()
This is described in the (combined) help page for the graphical formats ?png, ?bmp, ?jpeg and ?tiff as well as in the separate help page for ?pdf.
Note however that the image might look different on disk to the same plot directly plotted to your screen, for example if you have resized the on-screen window.
Note that if your plot is made by either lattice or ggplot2 you have to explicitly print the plot. See this answer that explains this in more detail and also links to the R FAQ: ggplot's qplot does not execute on sourcing
2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.
dev.print(pdf, 'filename.pdf')
This should copy the image perfectly, respecting any resizing you have done to the interactive window. You can, as in the first part of this answer, replace pdf with other filetypes such as png.
If you want to keep seeing the plot in R, another option is to use dev.copy:
X11 ()
plot (x,y)
dev.copy(jpeg,filename="plot.jpg");
dev.off ();
If you reach a clutter of too many plot windows in R, use graphics.off() to close all of the plot windows.
If you use ggplot2 the preferred way of saving is to use ggsave. First you have to plot, after creating the plot you call ggsave:
ggplot(...)
ggsave("plot.png")
The format of the image is determined by the extension you choose for the filename. Additional parameters can be passed to ggsave, notably width, height, and dpi.
Like this
png('filename.png')
# make plot
dev.off()
or this
# sometimes plots do better in vector graphics
svg('filename.svg')
# make plot
dev.off()
or this
pdf('filename.pdf')
# make plot
dev.off()
And probably others too. They're all listed together in the help pages.
For the first question, I find dev.print to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk
dev.print(pdf, file="filename.pdf");
You can replace pdf with other formats such as png.
This will copy the image exactly as you see it on screen. The problem with dev.copy is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.
For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands
pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor
If you use R Studio http://rstudio.org/ there is a special menu to save you plot as any format you like and at any resolution you choose
If you open a device using png(), bmp(), pdf() etc. as suggested by Andrie (the best answer), the windows with plots will not pop up open, just *.png, *bmp or *.pdf files will be created. This is convenient in massive calculations, since R can handle only limited number of graphic windows.
However, if you want to see the plots and also have them saved, call savePlot(filename, type) after the plots are drawn and the window containing them is active.
plotpath<- file.path(path, "PLOT_name",paste("plot_",file,".png",sep=""))
png(filename=plotpath)
plot(x,y, main= file)
dev.off()
To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:
R < myscript.R --no-save
This could be converted to jpg/png as necessary
In some cases one wants to both save and print a base r plot. I spent a bit of time and came up with this utility function:
x = 1:10
basesave = function(expr, filename, print=T) {
#extension
exten = stringr::str_match(filename, "\\.(\\w+)$")[, 2]
switch(exten,
png = {
png(filename)
eval(expr, envir = parent.frame())
dev.off()
},
{stop("filetype not recognized")})
#print?
if (print) eval(expr, envir = parent.frame())
invisible(NULL)
}
#plots, but doesn't save
plot(x)
#saves, but doesn't plot
png("test.png")
plot(x)
dev.off()
#both
basesave(quote(plot(x)), "test.png")
#works with pipe too
quote(plot(x)) %>% basesave("test.png")
Note that one must use quote, otherwise the plot(x) call is run in the global environment and NULL gets passed to basesave().
dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()

Use for loop to plot multiple figures and output them to pdf file, But just get the last figure [duplicate]

I know that
pdf("myOut.pdf")
will print to a PDF in R. What if I want to
Make a loop that prints subsequent graphs on new pages of a PDF file (appending to the end)?
Make a loop that prints subsequent graphs to new PDF files (one graph per file)?
Did you look at help(pdf) ?
Usage:
pdf(file = ifelse(onefile, "Rplots.pdf", "Rplot%03d.pdf"),
width, height, onefile, family, title, fonts, version,
paper, encoding, bg, fg, pointsize, pagecentre, colormodel,
useDingbats, useKerning)
Arguments:
file: a character string giving the name of the file. For use with
'onefile=FALSE' give a C integer format such as
'"Rplot%03d.pdf"' (the default in that case). (See
'postscript' for further details.)
For 1), you keep onefile at the default value of TRUE. Several plots go into the same file.
For 2), you set onefile to FALSE and choose a filename with the C integer format and R will create a set of files.
Not sure I understand.
Appending to same file (one plot per page):
pdf("myOut.pdf")
for (i in 1:10){
plot(...)
}
dev.off()
New file for each loop:
for (i in 1:10){
pdf(paste("myOut",i,".pdf",sep=""))
plot(...)
dev.off()
}
pdf(file = "Location_where_you_want_the_file/name_of_file.pdf", title="if you want any")
plot() # Or other graphics you want to have printed in your pdf
dev.off()
You can plot as many things as you want in the pdf, the plots will be added to the pdf in different pages.
dev.off() closes the connection to the file and the pdf will be created and you will se something like
> dev.off()
null device 1

multiple graphs pdf R

I would like to print multiple graphs in one pdf file. I know there has been a lot on this, but I would like to print different window/graph sizes for each page, i.e. first page a 8.5x11, second page 11x8.5 and so on. I tried this:
pdf(file="Combined_Graphs.pdf",onefile=TRUE,bg="white",width=8.5,height=11)
hist(rnorm(100))
pdf(file="Combined_Graphs.pdf",onefile=TRUE,width=11, height=8.5, bg="white")
hist(rnorm(100,10,2),col="blue")
dev.off()
I must be using onefile=TRUE wrong as it only generates the last graphic before closing. Is there a better way to size the graphic device without having to call the pdf function twice?
What I would do is produce seperate PDF's and them combine them later. I use the PDF toolkit for this. Wrapping this in an R function using a system call through system even makes it scriptable from R. The call to pdftk will look something like:
pdftk *pdf cat output combined.pdf
or in R:
system("pdftk *pdf cat output combined.pdf")
combine_pdfs = function(path, output_pdf) {
system(sprintf("pdftk %s/*pdf cat output %s"), path, output_pdf)
}
I think what you are trying to do cannot be done in R, i.e., you need to use external tools such as the PDF toolkit as suggested by Paul Hiemstra to combine separate PDF files with varying page dimensions (an alternative tool is PDFjam).
If you set onefile = TRUE in your call to pdf(), each plot that is written to that PDF device will be printed on a separate page, yet with the same page dimensions. In your example, you open a first PDF device, write one plot to it, then you open a second PDF device, write a different plot to it, and then close the second PDF device but leave the first PDF device open. Since you use the same file argument for both pdf() calls, you might not notice that the first PDF device is still open. If you closed it, only the first plot would end up in "Combined_Graphs.pdf".
Here is a modified version of your example that illustrates how PDF devices are opened, filled with content, and closed:
pdf(file = "foo.pdf", onefile = TRUE, width = 8.5, height = 11)
hist(rnorm(100))
hist(rnorm(100, 10, 2), col = "red")
pdf(file = "bar.pdf", width =11, height = 8.5)
hist(rnorm(100, 10, 2), col = "blue")
dev.off()
dev.off()

Print to PDF in a for loop

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

Resources