How to add title to colorbar legend in xyplot (lattice package)?

I reproduce the number 5.6 in the book "Lattice" by Dipayan Sarkar, although it uses one panel. Right now I'm struggling to get the title over the color bar ...

Here is some reproducible code.

x <- seq(1,20,.1)
y <- rnorm(length(x))
z <- seq(1,200,length.out=length(x))

cols <- rainbow(100)[cut(z,100,label=F)]

xyplot(y~x, aspect="iso", type=c("p","g"), col=1, pch=21,fill=cols,
   legend=list(right=
       list(fun = draw.colorkey,
            args=list(key=list(col = rainbow,at = do.breaks(range(z),100))))),
panel=function(x,y,...){
panel.xyplot(x,y,...)
}
)

Any clue? Thank,

AND

+4
source share
1 answer

It draw.colorkeydoesn't seem to respect the title=list property key=for any reason. But you can specify your own grob. Here we use packGrob(from grid) to change the standard colorkeygrob. try it

library(grid)
my.legend <- packGrob(
    draw.colorkey(key=list(col = rainbow, at = do.breaks(range(z),100))), 
    textGrob("My title", x = 0, y = 0.5, just = c("left", "centre")), 
    height=unit(2, "lines"),side="top", dynamic=T)

xyplot(y~x, aspect="iso", type=c("p","g"), col=1, pch=21,fill=cols,
    legend=list(right=list(fun=my.legend)))

enter image description here

+3
source

All Articles