AnjaM
AnjaM

Reputation: 3039

writing png plots into a pdf file in R

I have to create a bunch of graphs with a lot of data points. So far, I've been doing this by plotting all of them into one pdf-file:

pdf("testgraph.pdf")  
par(mfrow=c(3,3))

for (i in 2:length(names(mtcars))){
  plot(mtcars[,1], mtcars[,i])
}

dev.off()

However, with a lot of data points the pdf file becomes too large. As I'm not interested in outstanding quality, I don't care if my plots are vector graphics or not. So I thought of creating the plots as png and subsequently inserting them into a pdf file. Is there a way to do this except of creating R graphs and inserting them into pdf with knitr (which I think is too tedious for such a simple job)?

Upvotes: 15

Views: 9372

Answers (4)

Ajay
Ajay

Reputation: 454

The accepted answer does the writing and reading of png files sequentially. I wanted to read the png much later after it was written. So I used this solution:

pdf("testgraph.pdf")
p1 <- readPNG("testgraph.png", native = FALSE)
grid.raster(p1, width=unit(0.5, "npc"), height= unit(0.7, "npc"))
dev.off()

If there are multiple png files to be written to a pdf file in different pages then plot.new() can be used in a for loop (for loops are less efficient than alternatives in R but probably easier to explain the concept).

pdf("testgraph.pdf")
for (i in 1:nFiles) {
    p1 <- readPNG(paste0("testgraph",i,".png"), native = FALSE)
    grid.raster(p1, width=unit(0.5, "npc"), height= unit(0.7, "npc"))
    plot.new()
}
dev.off()

Upvotes: 0

BenBarnes
BenBarnes

Reputation: 19454

You can

  1. create .png files of each plot
  2. use the png package to read those back in and
  3. plot them in a pdf using grid.arrange
library(png)
library(grid)
library(gridExtra)

thePlots <- lapply (2:length(names(mtcars)), function(i) {
  png("testgraph.png")
  plot(mtcars[,1], mtcars[,i])

  dev.off()
  rasterGrob(readPNG("testgraph.png", native = FALSE),
    interpolate = FALSE)
})

pdf("testgraph.pdf")
do.call(grid.arrange, c(thePlots, ncol = 3))
dev.off()

Upvotes: 17

Greg Snow
Greg Snow

Reputation: 49660

If the source of the problem is too many points in the plot then you might want to consider using hexagonal binning instead of a regular scatterplot. You can use the hexbin package from bioconductor or the ggplot2 package has hexagonal binning capabilities as well. Either way you will probably get a more meaningful plot as well as smaller file size when creating a pdf file directly.

Upvotes: 6

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32401

You can convert the PNG files to PDF with ImageMagick

for i in *.png
do
  convert "$i" "$i".pdf
done

and concatenate the resulting files with pdftk.

pdftk *.png.pdf output all.pdf

Upvotes: 3

Related Questions