austin
austin

Reputation: 117

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?

Upvotes: 7

Views: 3715

Answers (2)

Thomas Zumbrunn
Thomas Zumbrunn

Reputation: 146

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

Upvotes: 5

Paul Hiemstra
Paul Hiemstra

Reputation: 60964

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

Upvotes: 7

Related Questions