using R to generate publication-quality figures

By , on

I am currently in the process of writing a book, and I plan to produce several figures for this project using the statistical computing package R. While R is generally quite good at creating scientific graphics, some adjustments help to create high-quality images for inclusion in another document. This blog entry gives some simple hints about the required steps.

  • Including figures in LaTeX: My aim is to create figures which can be included in a LaTeX document as follows:
    \documentclass{article}
    \usepackage{graphicx}
    \begin{document}
    
    Some useful information is shown in figure~\ref{figure1}.
    
    \begin{figure}
      \begin{center}
        \includegraphics{figure1}
      \end{center}
      \caption{\label{figure1}This is a figure.  It shows useful information.}
    \end{figure}
    
    \end{document}
    
  • PDF output: The figures need to be generated in one of the image formats supported by LaTeX. To get high-quality output it is best to avoid raster-based formats like JPG or PNG. Since I use pdfLaTeX, the most convenient file format for my figures is PDF. R can directly generate a PDF file from a script: This can be achieved with the pdf() command. The required calls are as follows:
    pdf("figure1.pdf", width=4.6, height=3)
    ...commands to generate the plot
    invisible(dev.off())
    

    The options width and height give the outer dimensions of the plot (including labels and margins) in inches. The dev.off() command at the end is required to make sure all output is written to the PDF file. I enclose dev.off inside invisible() in order to suppress an annoying message about the "null device" being printed to the screen.

  • Reproducability: for scientific use, it is important that the plot can be easily recreated at a later time. For this reason, I find it useful to create a separate R source file for every plot. For example, the file figure1.R might contain the R code required to generate figure1.pdf. On Linux and MacOS we can use a shebang-line to turn the R-script into a stand-alone program. This requires two steps: First, we have to add a line like the following at the start of the R script:
    #! /usr/bin/env Rscript
    pdf("figure1.pdf", width=4.6, height=3)
    ...commands to generate the plot
    invisible(dev.off())
    

    And secondly, we need to make the script executable by using (in a terminal window) a command like chmod +x figure1.R. After these steps, figure1.R can simply be executed to regenerate figure1.pdf. This particularly useful for use in Makefiles to automatically regenerate the figure every time the R script is changed.

Newer entry: neat trick!
Older entry: Wisent release 0.6.2

Back to blog