On 23/04/2012 10:49 AM, Adam Wilson wrote:
I routinely write graphics into multi-page PDFs, but some graphics (i.e.
plots of large spatial datasets using levelplot()) can result in enormous
files.  I'm curious if there is a better way.  For example:

#First, make some data:
library(lattice)
d=expand.grid(x=1:1000,y=1:1000)
d$z=rnorm(nrow(d))

#Now, the PDF.  The following produces a PDF that's ~50MB.
pdf(width=11,height=8.5,file="test1.pdf")
levelplot(z~x*y,data=d)
dev.off()

#If you write the same graphic to a png with reasonable resolution, the
file size is ~500k:
png(width=1024,height=768,file="test1.png")
levelplot(z~x*y,data=d)
dev.off()

#  I would prefer to embed a png (or other raster format) inside a PDF
directly from R.
#  Is this possible?  I'm looking for some way to achieve something like
the following (of course this doesn't work):
pdf(width=11,height=8.5,file="test1.pdf")
      png(width=1024,height=768,file="current device")
              levelplot(z~x*y,data=d)
      dev.off()
dev.off()


Of course the PDF preserves vector scalability, but there are times it's
not worth the extra file size.  And you can write out the png's as separate
files and then merge them with imagemagick or ghostscript.  I currently get
around this by writing the graphics to a potentially very large (>>100MB)
PDF, then use ghostscript to convert *only* the large pages of the pdf to
png and put it back together as a PDF (a function I wrote for this is
described here:
http://planetflux.adamwilson.us/2010/06/shrinking-rs-pdf-output.html).

I'm curious if there is a way to do it directly by instructing R to write a
png and embed it within the already open PDF device.  Any ideas?

I haven't tried this, but rasterImage() can plot to PDF. So you just need to get your PNG display into a raster image.

Duncan Murdoch

______________________________________________
R-help@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.

Reply via email to