rlevelplot

Add title to levelplot colorkey R


How can I add a horizontal title to levelplot colorkey?

library(raster)
library(rasterVis)
r <- raster(ncol=10,nrow=10)
r[] <- sample(c(1:3),size=100,replace=T)
r1 <- raster(ncol=10,nrow=10)
r1[] <- sample(c(1:9),size=100,replace=T)
r2 <- raster(ncol=10,nrow=10)
r2[] <- sample(c(5:15),size=100,replace=T)
r3 <- raster(ncol=10,nrow=10)
r3[] <- sample(c(3:35),size=100,replace=T)
s <- stack(r,r1,r2,r3)

breaks <- 7
my.at <- round(seq(min(minValue(s)), max(maxValue(s)), length.out = breaks),digits=2)
myColorkey <- list(space = "bottom",title="some number of days",at=my.at,height=0.95, width=1, labels=list(at=my.at,cex=1.1))
levelplot(s,at=my.at,colorkey = myColorkey)

enter image description here


Solution

  • From the docs you can have a horizontal title on the top or the bottom of the colorbar using the title.control= argument, e.g. title.control = list(side = "top") to put the title on the top:

    library(raster)
    #> Loading required package: sp
    library(rasterVis)
    #> Loading required package: lattice
    
    set.seed(123)
    
    r <- raster(ncol = 10, nrow = 10)
    r[] <- sample(3, size = 100, replace = T)
    r1 <- raster(ncol = 10, nrow = 10)
    r1[] <- sample(9, size = 100, replace = T)
    r2 <- raster(ncol = 10, nrow = 10)
    r2[] <- sample(5:15, size = 100, replace = T)
    r3 <- raster(ncol = 10, nrow = 10)
    r3[] <- sample(3:35, size = 100, replace = T)
    s <- stack(r, r1, r2, r3)
    
    breaks <- 7
    my.at <- round(seq(min(minValue(s)), max(maxValue(s)),
      length.out = breaks
    ), digits = 2)
    myColorkey <- list(
      space = "bottom", title = "some number of days",
      at = my.at, height = 0.95, width = 1,
      labels = list(at = my.at, cex = 1.1),
      title.control = list(side = "top")
    )
    levelplot(s, at = my.at, colorkey = myColorkey)