Removing white space around R figures

When I want to insert fig­ures gen­er­ated in R into a LaTeX doc­u­ment, it looks bet­ter if I first remove the white space around the fig­ure. Unfor­tu­nately, R does not make this easy as the graphs are gen­er­ated to look good on a screen, not in a document.

There are two things that can be done to fix this problem.

First, you can reduce the white space gen­er­ated by R. I use the fol­low­ing func­tion when sav­ing fig­ures in R.

savepdf <- function(file, width=16, height=10)
{
  fname <- paste("figures/",file,".pdf",sep="")
  pdf(fname, width=width/2.54, height=height/2.54,
      pointsize=10)
  par(mgp=c(2.2,0.45,0), tcl=-0.4, mar=c(3.3,3.6,1.1,1.1))
}

The width and height are in cen­time­tres. The ratio is about right for a beamer pre­sen­ta­tion, and also to fit two fig­ures on an A4 page.

Then I use the commands

savepdf("filename")
# Plotting commands here
dev.off()

That will gen­er­ate a pdf fig­ure of about the right size and shape for a doc­u­ment, and with nar­row mar­gins of white space, and save it in my fig­ures sub-​​directory.

The sec­ond trick is to trim the pdf files so there is no white space left. On a unix sys­tem, this is eas­ily achieved as follows.

pdfcrop filename.pdf filename.pdf

There are prob­a­bly win­dows and mac ver­sions of the same, but I haven’t used them. Adobe Acro­bat will also crop pdfs, but not from the com­mand line as far as I know.

To apply pdfcrop to every file in a direc­tory (using unix), save the fol­low­ing to a file called cropall.sh:

#!/bin/bash
 
for FILE in ./*.pdf; do
  pdfcrop "${FILE}" "${FILE}"
done

Make the file exe­cutable and run it.

In my post on Make­files, I explain how to include pdfcrop within a Makefile.

If you just use pdfcrop with­out first reduc­ing the white space in R, the pro­por­tions come out a lit­tle odd. So I tend to use both approaches together.


Related Posts:


  • ozi

    Instead of using pdfcrop in a bash script, I put the fol­low­ing in my R code:
    system(paste(“pdfcrop”, file­name, filename))

    • http://robjhyndman.com Rob J Hyndman

      Good idea. That makes it neater.

    • con­ju­gateprior

      Or, since R 2.12, the rather more reli­able: system2(‘pdfcrop’, c(‘filename1’, ‘filename2’))

  • http://yihui.name/ Yihui Xie
  • http://twitter.com/thurnherr Tom

    Hi Rob!

    Nice post! Another way is to let LaTeX trim the fig­ures using the graph­ics bun­dle. Here is a post I wrote on that topic.

    Best, Tom.

    • http://robjhyndman.com Rob J Hyndman

      It is a shame that the trim­ming func­tion in include­graph­ics can’t auto­mat­i­cally remove white­space with­out the user spec­i­fy­ing the dis­tances. That’s why I pre­fer pdfcrop — you do not need to fig­ure out the dis­tances yourself.

  • Paul Rubin

    Those of us using LyX can set a crop­ping win­dow within LyX.

  • Pingback: Removing white space around R figures « AstroNayla()