Search code examples
rplotrasterr-raster

R: Plot and Save rasterbrick layers separately with common legend scale


I have a multiband rasterbrick object and I am looking for an efficient solution to plot and save each of those separately in .jpg format. I cannot use spplot() or levelplot() because the object has 100 layers.

Currently I plan to write each of the layers as separate .tiff and use Arcgis to plot. Here is the layer I am working on.


Solution

  • You could write a function to save JPEG plots then use sapply

    library(raster)
    
    rand_raster <- function() {
      r <- raster(nrows = 10, ncols = 10)
      r[] <- runif(100)
      r
    }
    
    s <- brick(rand_raster(), rand_raster(), rand_raster())
    breaks <- seq(from = min(summary(s)["Min.", ]),
                  to = max(summary(s)["Max.", ]),
                  length.out = 5)
    palette <- colorRampPalette(colors = c("blue", "red"))
    cols <- palette(5)
    
    raster_plot <- function(x, s) {
      jpeg(filename = paste(names(s[[x]]), ".jpg"))
      plot(s[[x]], breaks = breaks, col = cols)
      dev.off()
    }
    
    sapply(1:nlayers(s), function(x) raster_plot(x, s))