[Tex/LaTex] exporting R ggplot2 plots to LaTex

r

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?

Best Answer

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.