Home > Doc > An Introduction to R > Low-level plotting commands

An Introduction to R

Low-level plotting commands

Sometimes the high-level plotting functions don’t produce exactly the kind of plot you desire. In this case, low-level plotting commands can be used to add extra information (such as points, lines or text) to the current plot. Some of the more useful low-level plotting functions are:

points(x, y)

lines(x, y) Adds points or connected lines to the current plot. plot()’s type= argument can also be passed to these functions (and defaults to "p" for points() and "l" for lines().)

text(x, y, labels, ...) Add text to a plot at points given by x, y. Normally labels is an integer or character vector in which case labels[i] is plotted at point (x[i], y[i]). The default is 1:length(x). Note: This function is often used in the sequence

> plot(x, y, type="n"); text(x, y, names)

The graphics parameter type="n" suppresses the points but sets up the axes, and the text() function supplies special characters, as specified by the character vector names for the points.

abline(a, b)

abline(h=y)

abline(v=x)

abline(lm.obj) Adds a line of slope b and intercept a to the current plot. h=y may be used to specify y-coordinates for the heights of horizontal lines to go across a plot, and v=x similarly for the x-coordinates for vertical lines. Also lm.obj may be list with a coefficients component of length 2 (such as the result of model-fitting functions,) which are taken as an intercept and slope, in that order.

polygon(x, y, ...) Draws a polygon defined by the ordered vertices in (x, y) and (optionally) shade it in with hatch lines, or fill it if the graphics device allows the filling of figures.

legend(x, y, legend, ...) Adds a legend to the current plot at the specified position. Plotting characters, line styles, colors etc., are identified with the labels in the character vector legend. At least one other argument v (a vector the same length as legend) with the corresponding values of the plotting unit must also be given, as follows:

legend( , fill=v) Colors for filled boxes

legend( , col=v) Colors in which points or lines will be drawn

legend( , lty=v) Line styles

legend( , lwd=v) Line widths

legend( , pch=v) Plotting characters (character vector)

title(main, sub) Adds a title main to the top of the current plot in a large font and (optionally) a sub-title sub at the bottom in a smaller font.

axis(side, ...) Adds an axis to the current plot on the side given by the first argument (1 to 4, counting clockwise from the bottom.) Other arguments control the positioning of the axis within or beside the plot, and tick positions and labels. Useful for adding custom axes after calling plot() with the axes=FALSE argument.

Low-level plotting functions usually require some positioning information (e.g., x and y coordinates) to determine where to place the new plot elements. Coordinates are given in terms of user coordinates which are defined by the previous high-level graphics command and are chosen based on the supplied data. Where x and y arguments are required, it is also sufficient to supply a single argument being a list with elements named x and y. Similarly a matrix with two columns is also valid input. In this way functions such as locator() (see below) may be used to specify positions on a plot interactively.

Mathematical annotation

In some cases, it is useful to add mathematical symbols and formulae to a plot. This can be achieved in R by specifying an expression rather than a character string in any one of text, mtext, axis, or title. For example, the following code draws the formula for the Binomial probability function:

> text(x, y, expression(paste(bgroup("(", atop(n, x), ")"), p^x, q^{n-x})))

More information, including a full listing of the features available can obtained from within R using the commands:

> help(plotmath)

> example(plotmath)

> demo(plotmath)

Hershey vector fonts

It is possible to specify Hershey vector fonts for rendering text when using the text and contour functions. There are three reasons for using the Hershey fonts:

• Hershey fonts can produce better output, especially on a computer screen, for rotated and/or small text.

• Hershey fonts provide certain symbols that may not be available in the standard fonts. In particular, there are zodiac signs, cartographic symbols and astronomical symbols.

• Hershey fonts provide cyrillic and japanese (Kana and Kanji) characters. More information, including tables of Hershey characters can be obtained from within R using the commands:

> help(Hershey)

> demo(Hershey)

> help(Japanese)

> demo(Japanese)

Interacting with graphics

R also provides functions which allow users to extract or add information to a plot using a mouse. The simplest of these is the locator() function:

locator(n, type) Waits for the user to select locations on the current plot using the left mouse button. This continues until n (default 512) points have been selected, or another mouse button is pressed. The type argument allows for plotting at the selected points and has the same effect as for high-level graphics commands; the default is no plotting. locator() returns the locations of the points selected as a list with two components x and y.

locator() is usually called with no arguments. It is particularly useful for interactively selecting positions for graphic elements such as legends or labels when it is difficult to calculate in advance where the graphic should be placed. For example, to place some informative text near an outlying point, the command

> text(locator(1), "Outlier", adj=0)

may be useful. (locator() will be ignored if the current device, such as postscript does not support interactive pointing.)

identify(x, y, labels) Allow the user to highlight any of the points defined by x and y (using the left mouse button) by plotting the corresponding component of labels nearby (or the index number of the point if labels is absent). Returns the indices of the selected points when another button is pressed. Sometimes we want to identify particular points on a plot, rather than their positions. For example, we may wish the user to select some observation of interest from a graphical display and then manipulate that observation in some way. Given a number of (x, y) coordinates in two numeric vectors x and y, we could use the identify() function as follows:

> plot(x, y)

> identify(x, y)

The identify() functions performs no plotting itself, but simply allows the user to move the mouse pointer and click the left mouse button near a point. If there is a point near the mouse pointer it will be marked with its index number (that is, its position in the x/y vectors) plotted nearby. Alternatively, you could use some informative string (such as a case name) as a highlight by using the labels argument to identify(), or disable marking altogether with the plot = FALSE argument. When the process is terminated (see above), identify() returns the indices of the selected points; you can use these indices to extract the selected points from the original vectors x and y.

Using graphics parameters

When creating graphics, particularly for presentation or publication purposes, R’s defaults do not always produce exactly that which is required. You can, however, customize almost every aspect of the display using graphics parameters. R maintains a list of a large number of graphics parameters which control things such as line style, colors, figure arrangement and text justification among many others. Every graphics parameter has a name (such as ‘col’, which controls colors,) and a value (a color number, for example.) A separate list of graphics parameters is maintained for each active device, and each device has a default set of parameters when initialized. Graphics parameters can be set in two ways: either permanently, affecting all graphics functions which access the current device; or temporarily, affecting only a single graphics function call.

Permanent changes: The par() function

The par() function is used to access and modify the list of graphics parameters for the current graphics device.

par() Without arguments, returns a list of all graphics parameters and their values for the current device.

par(c("col", "lty")) With a character vector argument, returns only the named graphics parameters (again, as a list.)

par(col=4, lty=2) With named arguments (or a single list argument), sets the values of the named graphics parameters, and returns the original values of the parameters as a list.

Setting graphics parameters with the par() function changes the value of the parameters permanently, in the sense that all future calls to graphics functions (on the current device) will be affected by the new value. You can think of setting graphics parameters in this way as setting “default” values for the parameters, which will be used by all graphics functions unless an alternative value is given. Note that calls to par() always affect the global values of graphics parameters, even when par() is called from within a function. This is often undesirable behavior—usually we want to set some graphics parameters, do some plotting, and then restore the original values so as not to affect the user’s R session. You can restore the initial values by saving the result of par() when making changes, and restoring the initial values when plotting is complete.

> oldpar <- par(col=4, lty=2)

. . . plotting commands . . .

> par(oldpar)

To save and restore all settable1 graphical parameters use

> oldpar <- par(no.readonly=TRUE)

. . . plotting commands . . .

> par(oldpar)

Temporary changes: Arguments to graphics functions

Graphics parameters may also be passed to (almost) any graphics function as named arguments. This has the same effect as passing the arguments to the par() function, except that the changes only last for the duration of the function call. For example:

> plot(x, y, pch="+")

produces a scatterplot using a plus sign as the plotting character, without changing the default plotting character for future plots. Unfortunately, this is not implemented entirely consistently and it is sometimes necessary to set and reset graphics parameters using par().

Next: Graphics parameters list

Summary: Index