# Figure functions

- -

Transitioning from an interactive plot in R to a publication-ready plot can create a messy script file with lots of statements and use of global variables. This post outlines an approach that I have used to simplify the process and keeps code readable.

The usual way of plotting to a file is to open a plotting device (such as pdf or png) run a series of commands that generate plotting output, and then close the device with dev.off(). However, the way that most plots are developed is purely interactively. So you start with:

Then to convert this into a figure for publication we copy and paste this between the device commands:

This leads to bits of code that often look like this:

which is all pretty ugly. On top of that, we’re often making a bunch of variables that are global but are really only useful in the context of the figure (in this case the fit object that contains the trend line). An arguably worse solution would be simply to duplicate the plotting bits of code.

## A partial solution:

The solution that I usually use is to make a function that generates the figure.

Then you can easily see the figure

or

and you can easily generate plots:

However, this still gets a bit unweildly when you have a large number of figures to make (especially for talks where you might make 20 or 30 figures).

## A full solution

The solution I use here is a little function called to.pdf:

Which can be used like so:

• It becomes much easier to read and compare the parameters to the plotting device (width, height, etc).
• We’re reduced things from 6 repetitive lines to 2 that capture our intent better.
• The to.pdf function demands that you put the code for your figure in a function.
• Using functions, rather than statements in the global environment, discourages dependency on global variables. This in turn helps identify reusable chunks of code.
• Arguments are all passed to pdf via ..., so we don’t need to duplicate pdf’s argument list in our function.
• The on.exit call ensures that the device is always closed, even if the figure function fails.

For talks, I often build up figures piece-by-piece. This can be done like so (for a two-part figure)

Now – if run with as

just the data are plotted, and if run as

the trend line and legend are included. Then with the to.pdf function, we can do:

which will generate the two figures.

The general idea can be expanded to more devices:

where we would do:

Note that with this to.dev function we can rewrite the to.pdf function more compactly:

Or write a similar function for the png device:

(As an alternative, the dev.copy2pdf function can be useful for copying the current contents of an interactive plotting window to a pdf).