Trellis Graphics in R

Trellis Graphics

Trellis graphics are a relatively new style of graphics in S and R that are particularly useful for displaying multivariate and especially grouped data.

Let's start with an example. The singer dataset contains the heights of several opera singers, grouped by the part they sing (Bass, Tenor, etc). Suppose we want to see the height distribution by group with a histogram for each group. This can be done as follows with standard R graphics:

data(singer, package = "lattice")
singer.split <- split(singer$height, singer$voice.part)
str(singer.split)

## split the screen into 8 parts and draw the histograms per group:

par(mfrow = c(2, 4)) ## multiple figure regions
lapply(singer.split, hist)

As you can see if you try this, the resulting plot is not very informative. It is possible to clean this up, but not easily.

Trellis plots can deal much better with such grouped displays. The relevant functions are available in the lattice package.

library(lattice)
histogram(~ height | voice.part, data = singer)

Here are a few other basic Trellis plot types:

## bwplot - box plots
bwplot(voice.part ~ height, data = singer)

## stripcharts
stripplot(voice.part ~ height, data = singer, jitter = TRUE)


## `Dot Plot'

dotplot(variety ~ yield | site, data = barley,
        groups = year, auto.key = list(space = "right"),
        xlab = "Barley Yield (bushels/acre) ",
        aspect=0.5, layout = c(1,6))


## Scatter plots
data(iris)
xyplot(Sepal.Length ~ Sepal.Width | Species, data = iris)
xyplot(Petal.Length ~ Petal.Width, data = iris,
       groups = Species, auto.key = TRUE)

## Scatter plot matrices
splom(~ iris[, 1:4] | Species, data = iris)
splom(~ iris[, 1:4], data = iris, groups = Species)

## 3-D scatter plots
cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris,
      groups = Species)
cloud(Sepal.Length ~ Petal.Length * Petal.Width | Species, data = iris,
      screen = list(x = -90, y = 70), distance = .4, zoom = .6)

One important note: Unlike standard R graphics functions, lattice functions do not draw the plots when they are executed. Rather, like other functions, they return an object (of class "trellis"), and the print method (print.trellis) actually draws the plot. So, you may need to print the object explicitly to see the plot.

h <- histogram(~ height | voice.part, data = singer) # nothing drawn
print(h)

More information is available from the online help pages and the official Trellis web site.

Last modified: Thu Jan 21 11:39:52 PST 2010