[R] scale caption on levelplot

Peter Ehlers ehlers at ucalgary.ca
Sat Dec 4 23:48:42 CET 2010


Andrew,
see below

On 2010-12-04 08:25, David Winsemius wrote:
>
> On Dec 4, 2010, at 8:25 AM, Andrew Collier wrote:
>
>> hi,
>>
>> i am trying to figure out how to put a caption on the colour scale
>> of a
>> levelplot. there does not seem to be an option for this in
>> levelplot().
>
> Agreed. I could not find one in the levelplot help page or in the
> chapter of Lattice on legends and keys. Sarkar basically says you need
> to use grid calls if you want to go beyond the basics.
>
>> i tried using mtext() but as soon as you put the text far out enough
>> on
>> the right of the plot, it goes beyond the plot boundary. so i tried to
>> extend the margin on the right of the plot using par(mar) but this did
>> not have any effect on the plot area.
>>
>> i would really appreciate some help with this because having a caption
>> on a colour scale is rather fundamental and certainly something that a
>> journal referee is going to pick up on!
>
> Your question has no reproducible example but suggests that you do not
> understand that levelplot is a lattice function and that lattice uses
> grid graphics. The par arguments that lattice understands (or is
> willing to deal with gracefully) are passed through trellis.par.set().
> The current settings are accessible with:
>
> trellis.par.get()
>
>    Since lattice is implemented with grid graphics, you may get useful
> information from:
>
> require(grid)   # lattice apparently loads gpar and its help page but
> doesn't
>                   # actually load grid. (I don't understand this. )
> ?gpar()   # Which has examples that may allow you to get a better
> understanding
>             # of how to layer new material on top of existing grid
> graphics.
>
As David says, you need to use trellis parameters, in this case
presumably trellis.par.get('layout.widths') and
trellis.par.get('layout.heights') will be useful. You can add
appropriate settings to your levelplot() call with the
par.settings argument. After you adjust the amount of space
you want, you can then use grid::grid.text() to add your text.
Here's an example:

   library(grid)
   x <- sort(rnorm(100,50,10))
   y <- sort(runif(100,0,20))
   d <- expand.grid(x=x, y=y)
   d$z <- x + y
   graphics.off()
   p <- levelplot(z ~ x*y, d,
             par.settings=list(
               layout.widths=list(right.padding=4),
               layout.heights=list(top.padding=6)),
             colorkey = TRUE)
   print(p)

   ## now add the text
   grid.text('here and there', x=.98, y=.5, rot=-90,
     gp = gpar(col=4,
         fontfamily="HersheyGothicEnglish", cex=2))
   grid.text('here\nand\nthere', x=.88, y=.92,
     gp = gpar(lineheight=.75, col=3))

Peter Ehlers



More information about the R-help mailing list