[R] Examples of multiple key grobs

Deepayan Sarkar deepayan at stat.wisc.edu
Fri Feb 18 03:38:54 CET 2005


On Thursday 17 February 2005 19:39, Patrick Connolly wrote:
> The xyplot help page gives quite a lot of information how to use key
> and indicates that legend needs to be used if multiple keys are
> needed.  However, it gives only a brief description of what the grob
> needs to contain to do multiple keys.

You may have a slight confusion. Each ``key'' has to be a single grob 
(but a grob can be arbitrarily complicated).

>  I've only used the occasional grid function in panel functions, so I
> don't have much of a sense of how grobs are constructed.  I've been
> unable to find examples of code used to do multiple keys and would
> appreciate being pointed in the direction of some.

You would need to read up on grid documentation to learn about grobs.  
lattice offers two functions that explicitly create grobs, namely 
draw.key and draw.colorkey. The second last example in 'demo(lattice)' 
has an example of shadowed text, which I've modified in the example 
below:


g1 <- textGrob(rep("Fancy text", 2),
               x = unit(.5, "npc") + unit(c(.5, 0), "mm"),
               y = unit(.5, "npc") + unit(c(0, .5), "mm"),
               gp = gpar(col = c("black", "red"), cex = 3))

g2 <- textGrob("This is \na text grob")

xyplot(rnorm(10) ~ rnorm(10),
       legend =
       list(inside =
            list(fun = draw.key,
                 x = .3, y = .7, 
                 args =
                 list(key = list(points = list(col = 1:3),
                                 text = list(letters[1:3])),
                      draw = FALSE)),
            bottom = list(fun = g1),
            top    = list(fun = g2)))


The 'inside' component illustrates how you can create grobs inline using 
a function. This is useful if you need to create your grobs at the time 
of printing (e.g. if it makes uses of trellis.par.get), but otherwise a 
more readable version of this example is:


g3 <-
    draw.key(key = list(points = list(col = 1:3),
             text = list(letters[1:3])),
             draw = FALSE)


xyplot(rnorm(10) ~ rnorm(10),
       legend =
       list(inside = list(fun = g3, x = .3, y = .7),
            bottom = list(fun = g1),
            top    = list(fun = g2)))

Hope that helps somewhat,

Deepayan




More information about the R-help mailing list