[R] Multi-page PDF using dev.copy2pdf(filename, onefile=TRUE)?
ilai
keren at math.montana.edu
Mon Feb 6 18:24:21 CET 2012
Doug,
dev.copy2pdf closes the connection after it's "done", so onefile is
meaningless. To look at each plot before copy to a single pdf, you
could open a pdf(...) but revert between it and your graphic device:
graphics.off()
plot(1:7, 1:7)
x11c<- dev.cur() # your current graphics device
pdf(file="test.pdf")
dev.set(which=x11c) # back from pdf
dev.copy() # copy
dev.set(which=x11c) # back to graphic
plot(1:5, 1:5,col=2,pch=2)
dev.copy()
dev.set(which=x11c)
# ... etc. however many more plots
# don't forget to close the pdf device at the end:
dev.off(which=x11c+1)
# Both plots are in 'test.pdf'
Depending on your application you might be able to simplify things
with dev.next/dev.prev, or wrap this sequence into a little helper
function to be used in a loop.
Enjoy,
Elai
On Mon, Feb 6, 2012 at 6:44 AM, Doug Hill <logickle at yahoo.com> wrote:
> Hi all. I want to generate a sequence of n plots and save them into a single PDF file, one plot per page. From the R docs and other sources I gather the basic way to do this is save plot 1 into a file then append the 2:n plots to the same file.
> This code shows my basic approach, but for some reason only the last plot is saved into the pdf. I've tried different variations (e.g. using onefile only in the second call, or only in the first), to no avail. The comments show what I see if I step through the code one line at a time:
> scratch<-function() {
> graphics.off()
> plot(1:7, 1:7) # Opens a graphics window and displays a 7-point plot in it, as expected
> dev.copy2pdf(file="test.pdf", onefile=TRUE) # I see the 7-point plot in Adobe reader, as expected
> plot(1:5, 1:5) # Overwrites in the graphics window the 7-point plot with a 5-point, as expected
> dev.copy2pdf(file="test.pdf", onefile=TRUE) # Overwrites test.pdf so that it contains only the 7-point plot
> }
> A couple things:
> (1) The reason I don't just use something like pdf(filename) plot(...) plot(...) dev.off() is that I also want to see the plots before they're saved (I pause after each plot() command). But according to the docs for dev.copy2pdf(), that function accepts the same args as pdf() does, including onefile.
> (2) I wrap my code in a function to be able to use it in the StatEt debugger in Eclipse.
> If you know what I'm doing wrong, or know of a different/better way, advise away! Thanks, Doug
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list