Search code examples
rplotlatticelevelplot

Raster or RGB data cube plotting with lattice package


Suppose I have this very simple 2x2 RGB datacube that I want to plot:

set.seed(2017)
dc <- array(runif(12), dim = c(2,2,3))

I can plot this just by rasterizing the datacube:

plot(as.raster(dc), interpolate = FALSE)

enter image description here

But I would like to plot this data cube with the lattice package (for uniformity sake since I am mainly using it for other plotting too).

Is this possible? I am looking at levelplot, but am not able to make it work.


Solution

  • Ok, this turned out to be quite an endeavor with levelplot.

    I convert the RGB hex color values from raster to integers, and then use these values to map them to the color palette of the raster.

    set.seed(2017)
    dc <- array(runif(12), dim = c(2,2,3))
    plot(as.raster(dc), interpolate = FALSE)
    
    # convert color hexadecimals to integers
    rgbInt <- apply(as.raster(dc), MARGIN = c(1,2), 
                 FUN = function(str){strtoi(substring(str, 2), base = 16)})
    
    rgbIntUnq <- unique(as.vector(rgbInt))
    
    lattice::levelplot(x = t(rgbInt), # turn so rows become columns
                       at = c(0,rgbIntUnq),
                       col.regions = sprintf("#%06X", rgbIntUnq[order(rgbIntUnq)]), # to hex
                       ylim = c(nrow(rgbInt) + 0.5, 1 - 0.5), # plot from top to bottom
                       xlab = '', ylab = '')
    

    enter image description here

    The legend can also be removed with colorkey = FALSE property.

    I wonder whether there are simpler ways to do the same.