Controlling Axes of R Plots

Posted on December 17th, 2012

[Since writing this post, I've uploaded an R package to CRAN that implements these ideas. Find out more at]

R has powerful graphical capabilities and I use it in all my papers to plot data and illustrate theoretical ideas. The default plot function, however, doesn't give the reader needed control over the axis labels. Below I've plotted the some data using the R defaults and then made several changes for comparison. I think the plot on the right looks much better. In this post, I'll show you how to make the changes.

fig0 The default plot function in R works something like this.

This code produces the following figure.


Notice three things about the figure above.

  1. The tick marks along the axes are too long.
  2. The tick mark labels along the vertical axis are written vertically.
  3. The tick mark labels are too far from the tick marks.
  4. The axis labels are too far from the axes.

Below I discuss in detail how to fix each of these issues.

Orienting the Tick Mark Labels

To make the desired changes, we need to not rely so heavily on the axis annotation of the plot function. Instead, I like to initiate the plot using the plot function and add in the notations later.

This code produces the following figure without any axes or axis labels.


Now, all we need to do is add the axes into the figure and add the axis labels. To do this, I simply call the axis() command twice, once for each side I want to add an axis to. A simply call to the box() function adds a box around the plot. The code below adds a box around the plot and the tick marks and tick mark labels.

This code creates the following figure.


This plot matches the first plot produced using the notations in the plot function, but gives more control. We can make a simple change to the command that adds the axis to the vertical axis by setting the las option. This orients the tick mark labels horizontally.


Now our tick mark labels along the vertical axis are labeled horizontally--the only way that really makes sense.

Length of Tick Marks

Let's now turn to the length of the tick marks. Use the tck option in the axis command to control the length of the tick marks.


Now that's more like it. Unfortunately, making the tick marks shorter has only made their labels appear even further from the plot.

Tick Mark Labels

Fixing the tick mark labels requires a little bit of trickery. I fix this by calling the axis() command twice for each axis to be created. The first call plots the tick marks, but no labels. The second call plots the labels, but no tick marks. But adjust the line option in the second call, the labels can be repositioned.


Axis Labels

All that is left is to add in the axis labels. This is done with a quick call to the mtext() command. Control the distance from the axis with the line command.