The update method of trellis plots allows one to modify a lattice plot after the initial call. But the update behaviour is more like replace than append. This differs from the ggplot2 idiom where each new layer is additive to what exists already. Is it possible to get this additive behaviour using lattice?
An example:
LL <- barchart(yield ~ variety | site, data = barley,
groups = year, stack = TRUE,
between=list(y=0.5),
scales = list(x = list(rot = 90)))
print(LL)

Now I want to add panel.text to the existing plot. Using update in the following way doesn't work:
update(LL, panel=function(...){
args <- list(...); panel.text(args$x, args$y+2, round(args$y, 0))
})

I know that I can use update by specifying all of the layers in the panel function:
update(LL, panel=function(...){
args <- list(...)
panel.barchart(...)
panel.text(args$x, args$y+2, round(args$y, 0))
})
This will work, but requires that I know what is already in the lattice plot - or that I refactor my code quite substantially.
Question: Is there a way of adding to the existing panel in update.trellis?
See layer from the latticeExtra package.
library(lattice)
library(latticeExtra)
LL <- barchart(yield ~ variety | site, data = barley,
groups = year, stack = TRUE,
between=list(y=0.5),
scales = list(x = list(rot = 90)))
LL + layer(panel.text(x, y, round(y, 0), data=barley))

Here is a way to do it without latticeExtra. Admittedly, it's more complicated and difficult than the latticeExtra route. However, the flexibility with this trellis.focus method might be more useful in other contexts.
barchart(yield ~ variety | site, data = barley,
groups = year, stack = TRUE,
between=list(y=0.5),
scales = list(x = list(rot = 90)))
panels = trellis.currentLayout()
for( i in seq_along(panels) ) {
ind = which( panels == i, arr.ind=TRUE )
trellis.focus("panel",ind[2],ind[1])
vars = trellis.panelArgs()
panel.text(vars$x,vars$y,round(vars$y,0))
}

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With