Customizing Lattice Graphics

Most lattice functions share common arguments; the same argument has a similar effect in multiple functions. This section describes what each of those arguments does. Additionally, this section explains how to fine-tune the output of lattice functions.

Lattice functions share many common arguments. Instead of explaining what each function does separately I’ll explain them in a single table. (Note that the default values for many of these arguments, in particular the panel functions, aren’t the same among functions.)

ArgumentDescription
xThe object to plot. May be a formula, array, numeric vector, or table.
dataWhen x is a formula, data is a data frame in which the function is evaluated.
allow.multipleSpecifies how to interpret formulas of the form y1 + y2 ~ X | Z (where X is a function of multiple variables and Z may also be a function of multiple variables). By default, if allow.multiple=TRUE, then the lattice function will plot both y1 ~ X | Z and y2 ~ X | Z superimposed on the same panel. However, if you set allow.multiple=FALSE, then the lattice function will plot I(y1 + y2) ~ X | Z (summing y1 + y2).
outerSpecifies whether to superimpose plots or not when allow.multiple=TRUE and multiple dependent variables are specified. When outer=FALSE, the plots are superimposed; when outer=TRUE, plots are shown in different panels.
box.ratioFor plots that show data in rectangles (bwplot, barchart, and stripplot), a numeric value that specifies the ratio of the width of the rectangles to the inner rectangle space.
horizontalFor plots that can be laid out vertically or horizontally (bwplot, dotplot, barchart and stripplot), a logical value that specifies the direction to plot.
panelThe panel function used to actually draw the plots.
aspectSpecifies the aspect ratio to use for different panels. Allowable values are aspect="fill" to fill the available space (the default), aspect="xy" to compute aspect ratios based on Cleveland’s 45° banking rule, and aspect="iso" for isometric scales.
groupsSpecifies a variable (or expression of variables) describing groups of data to pass to the panel function. In most cases, groups specifies the sets of values to show in different colors or with different symbols.
auto.keyA logical value specifying whether to automatically draw a key showing the names of groups corresponding to different colors or symbols. (The variables key and legend override auto.key.)
prepanelA function that takes the same arguments as panel and returns a list containing values xlim, ylim, dx, and dy (and, less frequently, xat and yat). The prepanel function is used to determine how much space is required to plot a panel. See the help files or [Sarkar2008] for more information.
stripA logical value specifying whether strips (that label panels) should be drawn.
xlabA character value specifying the label for the x-axis.
ylabA character value specifying the label for the y-axis.
scalesA list that specifies how the x- and y-axes should be drawn.
subscriptsA logical value specifying whether a vector named subscripts should be passed to the panel function. See the help files or [Sarkar2008] for more information.
subsetSpecifies the subset of values from data to plot. (By default, includes all values.) You can specify a logical vector or an expression that can be evaluated within data. (Note: be careful of NA values in subset vectors. Additionally, note that subset does not remove unused levels from plotted factors, so keys may contain these values.)
xlimSpecifies the minimum and maximum values for the x-axis.
ylimSpecifies the minimum and maximum values for the y-axis.
drop.unused.levelsA logical value (or a list outlining what to do for different components of x) specifying whether to drop unused levels of factors.
default.scalesA list giving the default value of scales. See the help files or [Sarkar2008] for more information.
lattice.optionsA list of plotting parameters, similar to par values for standard R graphics. See the help file for lattice.options for more information.
...Arguments passed to the internal function trellis.skeleton.

The following table shows arguments to trellis.skeleton, which are effectively arguments to all high-level Trellis functions even when not listed.

ArgumentDescription
as.tableSpecifies the order in which panels are drawn. Use as.table=FALSE to draw from left to right, bottom to top or as.table=TRUE to draw from left to right, top to bottom.
betweenA list with components x and y specifying the space between panels.
keyA list of arguments that define a legend of the components in the plot.
legendA list specifying a set of grid objects to be used as legends. See the help file for xyplot or [Sarkar2008] for more details.
pageA single-argument function to be called after drawing each page. (The argument is the page number.)
mainA character value or expression specifying the main title for the plot.
subA character value or expression specifying the subtitle for the plot.
par.strip.textA list of parameters that control the strip text. (Includes col, cex, lines, abbreviate, minlength, dot.)
layoutA numeric vector specifying the number of rows, columns, and pages. You may specify a value of 0 for a dimension to mean “fit in as many as needed for this dimension to meet my request for the other dimensions.” For example, c(1, 5) means “one column, five rows,” while c(0, 5) means “as many columns as are needed with exactly five rows.”
skipA logical vector specifying which panels to skip printing.
strip.leftA function to draw strips on the left side of each panel.
xlab.defaultDefault label for x-axis when xlab is not specified.
ylab.defaultDefault label for y-axis when ylab is not specified.
xscale.componentsA function to determine axis notation for the x-axis. See the help file for xscale.components.default for more information.
yscale.componentsA function to determine axis notation for the y-axis. See the help file for xscale.components.default for more information.
axisA function that draws axis notation. See the help file for axis.default for more information.
perm.condA numeric vector specifying a permutation of the conditioning variables. By default, the lattice functions draw panels in the order in which the conditioning variables are specified; this variable allows you to change that behavior. See the help file for more information.
index.condA list of functions that can be used to subset or reorder the array of conditioning variables. See the help file for xyplot for more information.
par.settingsA list of parameters, such as those set with trellis.par.set. See below for a list of available parameters.
plot.argsA list of arguments to plot.trellis. (See below for a table of arguments.)

You can control how axes are drawn in the lattice package by named values in the argument scales. You may specify a single list for x- and y-axes or specify a list of lists with separate x- and y-axes. (For example, to shrink all text by 50% and just plot the x-axis as a base 2 logarithm, use the argument scales=list(cex=.5, x = list(log = 2)).) Here is a table of the available arguments.

ArgumentDescription
relationDetermines how limits are calculated for each panel. Specify relation="same" to use the same scale, relation="free" to determine different limits in each panel, and relation="sliced" to keep the length the same in each panel but use different limits.
tick.numberSuggested number of tick marks. Ignored for character values, factors, and shingles.
drawA logical value specifying whether to draw the axis.
alternatingSpecifies whether to alternate axis locations between panels. Specify alternating=TRUE to alternate, alternating=FALSE not to alternate. Alternatively, you can specify a numeric vector that describes what to do with each panel: 0 not to draw axes, 1 to draw bottom/left, 2 to draw top/right, 3 to draw on both sides.
limitsLimits for each axis; equivalent to xlim and ylim.
atA numeric vector describing where to plot tick marks (in native coordinates) or a list describing where to plot tick marks for each panel.
labelsLabels to accompany at, specified as a vector (or list of vectors).
cexA numeric value that controls the size of axis labels (“character expansion” factor). Can specify a vector of length 2 to separately control left/bottom and right/top.
font, fontface, fontfamilySpecify typeface for axis labels.
tckA numeric value specifying the length of the tick marks.
colColor of tick marks and labels.
rotAngle to rotate axis labels. Can specify a vector of length 2 to separately control left/bottom and right/top.
abbreviateA logical value specifying whether to abbreviate labels using the function abbreviate.
minlengthAn argument passed to function abbreviate if argument abbreviate=TRUE.
logSpecifies whether to transform the data values to log scale prior to drawing and label the axis in log scale. Specify log=FALSE not to transform the values, log="e" to transform using a natural logarithm, or set log to another numeric value to use that base logarithm.
formatThe format to use for data/time variables; see the help file for strptime for more information.
axsUse axs="r" to pad date values on each side, axs="i" to use exact values.

In Graphical Parameters, we talked about the set of graphical parameters available with conventional graphics in R. As you may recall, you could use the function par to get or set default parameters. For example, to check the value of the parameter cex:

> par("cex")
[1] 1

The namespace is not hierarchical; every parameter has a single name. Currently, there are 70 different parameters available in the standard graphics package:

> length(par())
[1] 70

There is a similar mechanism for lattice graphics. It’s a little more complicated, but it’s also a lot easier to understand than a single list of named items, and it’s a lot more flexible.

To check the value of a setting, use the function trellis.par.get. As an example, let’s check the values of the "axis.text" parameter, which controls the look of text printed on axes:

> trellis.par.get("axis.text")
$alpha
[1] 1

$cex
[1] 0.8

$col
[1] "#000000"

$font
[1] 1

To change a setting, use trellis.par.set. To make the text even smaller, we could change the parameter axis.text$cex to 0.5 with the following command:

> trellis.par.set(list(axis.text = list(cex = 0.5)))

If you’d like a list of all settings, simply call trellis.par.get with no arguments. Or, even better, try the function show.settings, which shows all the settings graphically:

> show.settings()

An example of the output of show.settings is shown in Figure 14-32. Lattice graphics parameters are hierarchical; you can think of them as lists of lists. There are 34 high-level groups of parameters describing how different components are drawn:

> names(trellis.par.get())
 [1] "grid.pars"         "fontsize"          "background"
 [4] "clip"              "add.line"          "add.text"
 [7] "plot.polygon"      "box.dot"           "box.rectangle"
[10] "box.umbrella"      "dot.line"          "dot.symbol"
[13] "plot.line"         "plot.symbol"       "reference.line"
[16] "strip.background"  "strip.shingle"     "strip.border"
[19] "superpose.line"    "superpose.symbol"  "superpose.polygon"
[22] "regions"           "shade.colors"      "axis.line"
[25] "axis.text"         "axis.components"   "layout.heights"
[28] "layout.widths"     "box.3d"            "par.xlab.text"
[31] "par.ylab.text"     "par.zlab.text"     "par.main.text"
[34] "par.sub.text"

Here’s an explanation of what each of these groups of parameters controls:

grid.pars

A list of global parameters that can’t be set elsewhere, such as lex and lineend.

fontsize

Base font size for all text on the Trellis device.

background

Color of plot background.

clip

Controls clipping for panels and strips.

add.line, add.text

Specifies the appearance of lines or text plotted by helper functions like panel.grid and panel.text.

plot.polygon

Specifies the appearance of bars in panels generated by panel.barchart and panel.histogram.

box.dot, box.rectangle, box.umbrella

Specifies the appearance of points, rectangles, and umbrellas in panels plotted by panel.bwplot.

dot.line

Specifies the appearance of lines in panels plotted by panel.dotplot.

dot.symbol

Specifies the appearance of lines in symbols plotted by panel.dotplot.

plot.line

Specifies the appearance of lines plotted by panel.xyplot, panel.densityplot, and panel.cloud.

plot.symbol

Specifies the appearance of points plotted by panel.xyplot, panel.densityplot, and panel.cloud.

reference.line

Specifies the appearance of reference lines plotted by panel.grid and panel.text.

strip.background, strip.shingle, strip.border

Specifies the default appearance of strips.

superpose.line, superpose.symbol, superpose.polygon

Specifies the appearance of lines, symbols, and polygons on superimposed plots.

regions

Specifies how regions are plotted by panel.levelplot and panel.wireframe.

shade.colors

Specifies colors for plots by panel.levelplot and panel.wireframe.

axis.line, axis.text

Specifies how lines and text are plotted in axes.

axis.components

Controls the appearance of axes.

layout.heights, layout.widths

Controls the height and width of panels in a lattice.

box.3d

Specifies the way boxes are drawn by panel.cloud and panel.wireframe.

par.xlab.text, par.ylab.text, par.zlab.text

Controls how text labels are plotted.

par.main.text, par.sub.text

Specifies defaults for main and subtitles.

Within these groups, there are more parameters. There are a total of 378 parameters. However, there are only 46 unique parameters within these groups.[45] Here is an explanation of the most common subparameters (many of which are similar to standard graphical parameters):

alpha

Controls transparency.

border

Border color.

cex

Character expansion factor; size of this type relative to fontsize.

col

Color for lines and points.

fill

Color for fills.

font

Font face.

lineheight

Height of a line, as a multiple of text size.

lty

Line type.

lwd

Line width.

pch

Plotting character.

Here is an explanation of some of the nonstandard subparameters:

palette

Function generating color palette through parameter shade.colors.

text, points

Specifies text format through parameter fontsize.

panel, strip

Controls clipping for panels and strips in parameter clip.

top.padding, main, main.key.padding, key.top, key.axis.padding, axis.top, strip, panel, axis.panel, between, axis.bottom, axis.xlab.padding, xlab, xlab.key.padding, key.bottom, key.sub.padding, sub, bottom.padding

Parameters for layout.heights.

left.padding, key.left, key.ylab.padding, ylab, ylab.axis.padding, axis.left, axis.panel, strip.left, panel, between, axis.right, axis.key.padding, key.right, right.padding

Parameters for layout.widths.

For more information, see the help files for par (in the graphics package), gpar (in the grid package), or the help files for different panel functions.

As we noted above, lattice functions do not plot results; they return lattice objects. To plot a lattice object, you need to call print or plot on the lattice object.

The function that actually does the work is the plot.trellis function (which the help file claims is an alias for the print.trellis function). It’s possible to control how lattice objects are printed through arguments to plot.trellis. As shown above, you can also pass these arguments to lattice functions through the plot.args argument. Here’s a list of arguments for plot.trellis.

ArgumentDescriptionDefault
xThe Trellis object to plot. 
positionA vector of four numbers, c(xmin, ymin, xmax, ymax), specifying where to plot the object. Coordinates are between 0 and 1 for both dimensions. 
splitA vector of four integers, c(x, y, nx, ny) , that says to position the current plot at the x, y position in a regular array of nx by ny plots. 
moreA logical value specifying whether more plots will follow on the current page.FALSE
newpageA logical value specifying whether the plot should be on a new page.FALSE
packet.panelA function that determines which packet is plotted in which panel.packet.panel.default
draw.inA grid viewport in which to draw the plot.NULL
panel.heightA list of two components (x and units) specifying the height of each panel in the lattice plot. lattice.getOption("layout.heights")$panel
panel.widthA list of two components (x and units) specifying the width of each panel in the lattice plot. lattice.getOption("layout.widths")$panel
save.objectA logical value indicating whether to “save” the last object printed. See the help file for more information.lattice.getOption("save.object")
panel.errorA function that is executed if an error occurs while plotting the panel.lattice.getOption("panel.error")
prefixA character string to use as a prefix in viewport names, to distinguish similar plots. See the help file for more information. 
...Extra arguments: these are ignored. 

To change the way strips are drawn, you can specify your own strip function as an argument to a lattice function. Strip functions are a little complicated to write from scratch, so it is usually best to modify the strips by writing a new function that creates a wrapper around the function strip.default:

strip.default(which.given,
              which.panel,
              var.name,
              factor.levels,
              shingle.intervals,
              strip.names = c(FALSE, TRUE),
              strip.levels = c(TRUE, FALSE),
              sep = " : ",
              style = 1,
              horizontal = TRUE,
              bg = trellis.par.get("strip.background")$col[which.given],
              fg = trellis.par.get("strip.shingle")$col[which.given],
              par.strip.text = trellis.par.get("add.text"))

The simplest way to modify the appearance of the strips is by using the function strip.custom. This function accepts the same arguments as strip.default and returns a new function that can be specified as an argument to a lattice function.

Here’s a description of the arguments to strip.default (and, in turn, to strip.custom).

ArgumentDescriptionDefault
which.given, which.panel, var.name, factor.levels, shingle.intervalsThese arguments contain the data for actually drawing the strip. (Probably not needed for strip.custom.) 
strip.namesA logical vector with two elements that specifies whether to draw variable names in strips. strip.names[0] is used for factors and strip.names[1] for shingles.c(FALSE, TRUE)
strip.levelsA logical vector with two elements that specifies whether to draw variable values in strips. strip.names[0] is used for factors and strip.names[1] for shingles.c(TRUE, FALSE)
sepA character value specifying the separator if both name and level are shown. 
styleAn integer value specifying how the current level of a factor is encoded. See the help file for more information. 
horizontalA logical value specifying whether the labels should be horizontal. 
bgSpecifies the background color.trellis.par.get("strip.background") $col[which.given]
fgSpecifies the foreground color.trellis.par.get("strip.shingle") $col[which.given]
par.strip.textA list of parameters controlling the way text is drawn in the script (such as col, cex, font).trellis.par.get("add.text")

To customize the way that keys (or legends) are drawn for plots with multiple groups of variables, you may specify a custom function to the key argument, or you may use the auto.key argument to automatically draw a key using the simpleKey function. If you specify autoKey=TRUE, then simpleKey is called with the default arguments to generate the key. Alternatively, you can specify a list of arguments that are, in turn, passed as arguments to simpleKey to draw the legend:

simpleKey(text, points = TRUE,
          rectangles = FALSE,
          lines = FALSE,
          col, cex, alpha, font,
          fontface, fontfamily,
          lineheight, ...)
draw.key(key, draw=FALSE, vp=NULL, ...)

Here is a description of the arguments to simpleKey.

Argument(s)DescriptionDefault
textA character or expression vector specifying the text to be used to describe groups 
pointsA logical value specifying whether a key should be provided for pointsTRUE
rectanglesA logical value specifying whether a key should be provided as filled rectanglesFALSE
linesA logical value specifying whether a key should be provided for linesFALSE
col, cex, alpha, font, fontface, fontfamily, lineheightGraphical parameters that control different aspects of the key