[R] lattice key inside panel

Deepayan Sarkar deepayan.sarkar at gmail.com
Wed Feb 4 23:39:26 CET 2009


On Wed, Feb 4, 2009 at 2:13 PM, Iago Mosqueira <iago.mosqueira at gmail.com> wrote:
> Deepayan Sarkar wrote:
>> On Wed, Feb 4, 2009 at 8:21 AM, Iago Mosqueira <iago.mosqueira at gmail.com> wrote:
>>> Hello,
>>>
>>> I am trying to draw a key inside a single panel in a lattice xyplot. The
>>> panel function uses panel.number() to use a slightly different style for
>>> one of the panels. Once inside than panel I am using
>>>
>>> draw.key(list(text=list(lab='catch'),
>>>          lines=list(lwd=c(2)),
>>>          text=list(lab='landings'),
>>>          rectangles=list(col=rgb(0.1, 0.1, 0, 0.1)),
>>>         x=0, y=1, corner=c(0,0)), draw=TRUE)
>>>
>>> which gets me the key right in the middle of the panel. I would like to
>>> have at the top or bottom. Changes to the values of x, y or corner do
>>> not seem to change the position at all.
>>>
>>> lattice.getOption("legend.bbox") returns 'panel'.
>>>
>>> I am quit sure I am missing something essential, but can this be done
>>> without calling directly grid methods?
>>
>> No. The placement controls such as x, y, and corner are not handled by
>> draw.key itself, but rather by the high-level plotting function. Used
>> directly, draw.key() basically gives you a low-level grid "grob", and
>> you need to use grid tools to do anything with them ('draw=TRUE'
>> simply calls grid.draw() on the grob before returning it). The
>> simplest way to change position is to supply a simple 'vp' argument.
>>
>> xyplot(1~1,
>>        panel = function(...) {
>>            require(grid)
>>            panel.xyplot(...)
>>            draw.key(list(text=list(lab='catch'),
>>                          lines=list(lwd=c(2)),
>>                          text=list(lab='landings'),
>>                          rectangles=list(col=rgb(0.1, 0.1, 0, 0.1))),
>>                     draw = TRUE,
>>                     vp = viewport(x = unit(0.75, "npc"), y = unit(0.9, "npc")))
>>        })
>>
>>  More complex positioning (perhaps depending on the size of the
>> legend) will need more work.
>>
>> -Deepayan
>
> Thanks so much. This works perfectly.
>
> One other thing that has so far eluded me is how to specify two
> different kinds of symbols on a single column. The key above shows
>
> text line text rectangle
>
> but I would really like to get
>
> text line
> text rectangle
>
> but this did not seem possible to me. Am I wrong?

Not possible with draw.key(), but legends can be arbitrary grobs, so
you could construct a suitable one.

-Deepayan




More information about the R-help mailing list