Annotating Lattice Box and Whisker Plots

Submitted by dylan on Wed, 2010-04-28 20:54.

bwplot annotation examplebwplot annotation example

Sometimes you want to add a little text to box and whisker plots produced by the lattice function bwplot(). Here is one approach. Could be optimized a bit more to reduce manual specification of some elements. Suggestions welcomed.

Implementation also demonstrates adjusting lattice style parameters

# need this

# make some fake data
d <- data.frame(
rnorm(100, mean=1),
rnorm(100, mean=2),
rnorm(100, mean=0.5),
rnorm(100, mean=1)
g1=factor(rep(c('G1','G2'), each=200)),
g2=factor(rep(rep(c('A','B','C','D'), each=50),2))

# user-defined number of groups
n.groups <- 4

# comparison matrix- rows are panels, columns are groups
# these are computed elsewhere
comparison.matrix <- rbind(

bwplot(x ~ g2 | g1, data=d, subscripts=TRUE, notch=TRUE,
par.settings=list(plot.symbol=list(col=1, cex=0.75),, box.rectangle=list(col=1), box.umbrella=list(col=1)),
panel=function(x, y, n=n.groups, cm=comparison.matrix, ...) {
# basic bwplot
panel.bwplot(x, y, ...)
# compute offset from top of 'umbrella'
y.offset <- tapply(y, x, function(i) boxplot.stats(i)$stats[5])
# add text just above offset, by panel number
panel.text(1:n, y.offset + 0.25, cm[packet.number(), ], font=2)