Search code examples
rplotggplot2rasterlattice

Strips at top and side for conditioned RasterStack plot


For the following RasterStack, the individual layers are grouped according to two factors (upper case letters, and lower case letters).

library(raster)
s <- stack(replicate(6, raster(matrix(runif(100), 10))))
names(s) <- do.call(paste, c(expand.grid(LETTERS[1:2], letters[1:3]), sep='_'))
spplot(s)

enter image description here

I'd like to avoid repeating the levels' labels, ideally by having a single strip at the top with the labels A and B, and a single strip down the left or right side with labels a, b and c. Something like the following, but for a RasterStack.

library(latticeExtra)
useOuterStrips(
    xyplot(y~x|grp1+grp2, 
           data.frame(x=runif(600), y=runif(600), 
                      grp1=rep(LETTERS[1:2], each=100), 
                      grp2=rep(letters[1:3], 200)),
           strip=strip.custom(style=1), as.table=TRUE))

enter image description here

I'd like a lattice-based solution (including rasterVis::levelplot), since that way the plot I'm attempting to create will fit in nicely alongside other work. That said, I'm open to a ggplot2 solution.


Solution

  • I guess I was overthinking this...

    library(tidyr)
    cbind(as.data.frame(s), coordinates(s)) %>%
      gather(group, val, -x, -y) %>%
      separate(group, c('grp1', 'grp2'), '_') %>%
      levelplot(x=val~x+y|grp1+grp2, aspect='iso', 
                scales=list(alternating=FALSE, tck=1:0)) %>%
      useOuterStrips
    

    enter image description here