0

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?

perep1972
  • 147
  • 1
  • 9
  • I do not think it would be a great idea to try to have a combined legend in this case. Because, the values and colors show different things in these plots. For example, 80 is green on your first raster (left) while 80 is yellow(ish) in the second raster (right). – bird Jun 07 '21 at 15:19
  • This answer might be helpful: https://stackoverflow.com/a/21045393/9022665 – Jonathan V. Solórzano Jun 07 '21 at 15:28
  • 1
    Well, @bird, this is precisely part of what I want to fix. I tried by artificially replace values in both rasters to get the same ranks (the rasters I am working with are huge and such replacement would be used only for illustration purposes), but even so I was unable to get what I want – perep1972 Jun 07 '21 at 15:42
  • Thanks, @JonathanV.Solórzano, I already saw that one. However, I should put both rasters within the same rank, somehow. – perep1972 Jun 07 '21 at 15:44

1 Answers1

4

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