NavigationUser login |
Annotating Lattice Box and Whisker PlotsSubmitted by dylan on Wed, 2010-04-28 20:54.
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. # need this library(lattice) # make some fake data d <- data.frame( x=c( 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( c('a','b','c','c'), c('a','a','b','b') ) bwplot(x ~ g2 | g1, data=d, subscripts=TRUE, notch=TRUE, strip=strip.custom(bg=grey(0.85)), par.settings=list(plot.symbol=list(col=1, cex=0.75), box.dot=list(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) }) |