Search code examples
rlegendrasterlegend-properties

Combining rasters' legends in R language


Sorry for the evidently stupid question I haven't be able to solve, even after googleing for a while. Let's suppose the following situation, where I have two rasters with overlapping but different value ranks.

library(raster)
# A couple of rasters from scratch
r2 <- r1 <- raster(nrows=10, ncols=10)
r1[] <- sample(c(0:99), 100, replace = F)
r2[] <- sample(c(50:149), 100, replace = F)
par(mfrow = c(1,2))
plot(r1)
plot(r2)

enter image description here

How may I create the same plot but with only one legend ranging from 0 to 149, that is, the combined rank of both rasters?


Solution

  • Based on the answer I shared in the previous comment, you can manually set the breaks of the legend and the colors. Then you just need to apply that color ramp to both plots. Here's the code and the plot.

    # Adjust plot margins
    par(mar=c(2,2,2,5))
    
    # Set manually the breaks
    breaks = seq(0,150,25)
    pal <- colorRampPalette(c("white","orange","yellow","green","forestgreen"))
    
    plot(r1, breaks=breaks, col = pal(length(breaks)-1)) 
    plot(r2, breaks=breaks, col = pal(length(breaks)-1)) 
    

    plots