Skip to main content

3.6) Low-Level Functions: Adding To Plots


Once you have a plot, there are many functions that add features to the most recent plot. For example:

points() plots another data set on the same axes. Its arguments are like a slimmed-down version of plot(). The pch= argument is also useful here, to alter the plotting character for the new data (specified with numbers 1, 2, 3, etc), or add colours like col="red", or specify type= to plot with lines ("l") or points ("p") or both ("b").
abline() adds a straight line. You can specify the intercept and slope (two arguments), or an x-coordinate (v) for a vertical line, or a y-coordinate (h) for a horizontal line.
arrows() plots one or more arrows between the coordinates supplied using x0=, y0=, x1=, y1=. If you supply equal-length numeric vectors to all four arguments, an arrow is plotted for each element in the vectors. This is useful for adding error bars to a chart – specify angle=90, code=3 and find a suitable value for length= by trial and error.
polygon() adds a polygon formed by joining the dots between successive points in the arguments x=, y= (which should be equal-length vectors). The polygon can be shaded in various ways (e.g. using col=grey(0.7)). This can be useful if you’ve calculated confidence envelopes to add to a plot.
title() allows you to add a title to the latest plot.
legend() helps you create a legend. You need to specify everything you want, whether it’s lines, coloured or hatched boxes, etc, and the text for the key – so you’ll need to look at the help file. But if your graph comes from a plotting function that generates shading or different line-types automatically (like barplot() does when given a matrix), try just adding the argument legend=TRUE inside the plotting function (i.e. you don't need the legend() function).
text() adds text to the plotting space – e.g. text(x=c(1,1), y=c(0,1), labels=c("N = 20", "P < 0.001")).
mtext() adds text to the margins of a plot (useful for adding shared axis labels when you have several graphs in a single window (e.g. via par(mfrow=c(1,2))). The arguments are different from those of text(); e.g. mtext("length(mm)", outer=TRUE, side=2, las=0) would put a label in the outer margin of the left-hand side of the plotting window (side 2, counting clockwise from the bottom), and reading parallel to the axis (label style 0). Greater flexibility is available by specifying a margin-line(s) (line=) and/or position(s) (at=) for the text. Back to the help file…!