# exporting R ggplot2 plots to LaTex

I usually export ggplot2 plots from R using "Save As" PDF and works fine, then I use \includegraphics from LaTex to include the fig. The problem is that it seems that the amount of data in these exported PDF from R are big e.g. over 600K each. If I export several PDF documents like this, the end PDF is super laggy to open.

My question is: how can I change either R or load differently from LaTex so that the end document is not so big while the quality of the plots is still very high?

-
Have you tried with Sweave or knitr? I do not know if this solves this specific problem with ggplot2 plots, but I find effortless integrate R ouputs in latex that export every plot. I have made in this way documents with dozens of different R plots without problems. – Fran Aug 19 '12 at 11:24
Is it the complexity of your plots? Make a scatter plot of 10 points in ggplot, save as PDF, and tell us if that is huge. If you are plotting a million points on a ggplot, yes, the PDF will be large. And don't just say 'massive', we talk kilobytes and megabytes here. – Spacedman Aug 19 '12 at 14:53

If it gets to the point where a PDF is bigger than a PNG at a high resolution for your end use, then make a high-resolution PNG file. For example, for a figure that will be 4 inches square on a page for print, you want 300dpi x 4 = 1200 pixels. So do:

png(file="plot1.png",width=1200,height=1200)
makemyplot()
dev.off() # close the png file


The cutoff point for this will vary on how much the PNG compression algorithm can do and how much overlapping "ink" you've got - all the ink in a PDF takes space, but you can do a million points to a PNG at the same location and it will only be a few bytes.

There are also assorted PDF compression tools, but I'm guessing you're on Windows and I use Unix command-line tools. While I'm on about command line tools, you can probably convert existing PDFs to raster PNGs with the 'convert' tool from the ImageMagick suite.

But 600k isn't that big. I'm working on a book with 2 megabyte PDFs on almost every page.

-