Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to update a lattice panel in R?

Tags:

plot

r

lattice

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)

enter image description here

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))
         })

enter image description here

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?

like image 910
Andrie Avatar asked Oct 04 '11 14:10

Andrie


2 Answers

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))

result of code

like image 112
Aaron left Stack Overflow Avatar answered Oct 27 '22 22:10

Aaron left Stack Overflow


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))
}

Output of code above

like image 43
kdauria Avatar answered Oct 27 '22 22:10

kdauria