Search code examples
rrasterlevelplotrastervis

Change raster panel titles using levelplot


I'm using RasterVis and levelplot to make a trellis plot of some rasters. I am currently ok for most things but I would like to change the header for each panel from the filename to a chosen string (the filename is convoluted and long, i want to use just a year, for example '2004').

Looking at the levelplot page, it would indicate that levelplot goes looking for some settings as per the argument 'useRaster', either it goes to panel.levelplot or panel.levelplot.raster, but im struggling to use these latter functions.

Any help much appreciated, here's some sample code;

require(rasterVis)

layers <- c(1:4)
s2 <- stack()

for (i in layers) {
  r <- raster(nrows=100, ncols=100,ext)
  r[] <- sample(seq(from = 1, to = 6, by = 1), size = 10000, replace = TRUE)
  rasc <- ratify(r)
  rat <- levels(rasc)[[1]]
  rat$legend <- c("A","B","C","D","E","F")
  levels(rasc) <- rat
  s2 <- stack(s2, rasc)
}

levelplot(s2, col.regions=rev(terrain.colors(6)),main = "example")

In the above e.g., I would like "layer.1.1" to be "2004", and so on through to 2007


Solution

  • require(rasterVis)
    
    layers <- c(1:4)
    s2 <- stack()
    
    for (i in layers) {
      r <- raster(nrows=100, ncols=100)
      r[] <- sample(seq(from = 1, to = 6, by = 1), size = 10000, replace = TRUE)
      rasc <- ratify(r)
      rat <- levels(rasc)[[1]]
      rat$legend <- c("A","B","C","D","E","F")
      levels(rasc) <- rat
      s2 <- stack(s2, rasc)
    }
    levelplot(s2, col.regions=rev(terrain.colors(6)),main = "example", names.attr=2004:2007)
    

    enter image description here

    p.strip <- list(cex=1.5, lines=1, col="blue", fontfamily='Serif')
    
    levelplot(s2, col.regions=rev(terrain.colors(6)), main = "example",
              names.attr=2004:2007, par.strip.text=p.strip)
    

    enter image description here