Timtico
Timtico

Reputation: 387

R: dev.copy2pdf, multiple graphic devices to a single file, how to append to file?

I have a script that makes barplots, and opens a new window when 6 barplots have been written to the screen and keeps opening new graphic devices whenever necessary. Depending on the input, this leaves me with a potential large number of openened windows (graphic devices) which I would like to write to a single PDF file.

Considering my Perl background, I decided to iterate over the different graphics devices, printing them out one by one. I would like to keep appending to a single PDF file, but I do not know how to do this, or if this is even possible. I would like to avoid looping in R. :)

The code I use:

for (i in 1:length(dev.list())
{
dev.set(which = dev.list()[i]
dev.copy2pdf(device = quartz, file = "/Users/Tim/Desktop/R/Filename.pdf")
}

However, this is not working as it will overwrite the file each time. Now is there an append function in R, like there is in Perl. Which allows me to keep adding pages to the existing pdf file?

Or is there a way to contain the information in a graphic window to a object, and keep adding new graphic devices to this object and finally print the whole thing to a file?

Other possible solutions I thought about:

  1. writing different pdf files, combining them after creation (perhaps even possible in R, with the right libraries installed?)
  2. copying the information in all different windows to one big graphic device and then print this to a pdf file.

Upvotes: 7

Views: 9184

Answers (3)

DrAK
DrAK

Reputation: 1

I generate many separate pages and then join them with something like system('pdfjam pages.pdf -o output.pdf' )*

Upvotes: 0

petermeissner
petermeissner

Reputation: 12900

To further elaborate on the possibility to append to a pdf. Although, multiples graphs can be put easaly into one file it turns out that it is impossiple or at least not simple to really append a pdf once finished by dev.off() - see here.

Upvotes: 0

Dirk is no longer here
Dirk is no longer here

Reputation: 368489

Quick comments:

  1. use the onefile=TRUE argument which gets passed through to pdf(), see the help pages for dev.copypdf and pdf

  2. as a general rule, you may find it easier to open the devices directly; again see help(pdf)

So in sum, add onefile=TRUE to you call and you should be fine but consider using pdf() directly.

Upvotes: 5

Related Questions