Removing white space around R figures

When I want to insert figures generated in R into a LaTeX document, it looks better if I first remove the white space around the figure. Unfortunately, R does not make this easy as the graphs are generated 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 generated by R. I use the following function when saving figures 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,
  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 centimetres. The ratio is about right for a beamer presentation, and also to fit two figures on an A4 page.

Then I use the commands

# Plotting commands here

That will generate a pdf figure of about the right size and shape for a document, and with narrow margins of white space, and save it in my figures sub-directory.

The second trick is to trim the pdf files so there is no white space left. On a unix system, this is easily achieved as follows.

pdfcrop filename.pdf filename.pdf

There are probably windows and mac versions of the same, but I haven’t used them. Adobe Acrobat will also crop pdfs, but not from the command line as far as I know.

To apply pdfcrop to every file in a directory (using unix), save the following to a file called

for FILE in ./*.pdf; do
  pdfcrop "${FILE}" "${FILE}"

Make the file executable and run it.

In my post on Makefiles, I explain how to include pdfcrop within a Makefile.

If you just use pdfcrop without first reducing the white space in R, the proportions come out a little odd. So I tend to use both approaches together.

Related Posts:

  • ozi

    Instead of using pdfcrop in a bash script, I put the following in my R code:
    system(paste(“pdfcrop”, filename, filename))

    • Rob J Hyndman

      Good idea. That makes it neater.

    • conjugateprior

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

  • Yihui Xie

    This is also available in knitr as a hook function:

  • Tom

    Hi Rob!

    Nice post! Another way is to let LaTeX trim the figures using the graphics bundle. Here is a post I wrote on that topic.

    Best, Tom.

    • Rob J Hyndman

      It is a shame that the trimming function in includegraphics can’t automatically remove whitespace without the user specifying the distances. That’s why I prefer pdfcrop — you do not need to figure out the distances yourself.

  • Paul Rubin

    Those of us using LyX can set a cropping window within LyX.

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