Search code examples
rplotlegendrasterr-raster

Specifying different breakpoints of legends for raster in the same plot


If I want to provide my own classification of legend while plotting a raster, I could do this:

library(raster)
data(volcano)
volcanoR <- raster(volcano)

breakpoints <- c(94,100,120,140,160,180,195)
colors <- c("red","green4","blue","orange","pink","black")
plot(volcanoR,breaks=breakpoints,col=colors)

enter image description here

However, my data is some thing like this:

set.seed(123)

df <- data.frame(X=seq(1,30,by = 1), Y=seq(1,30,by=1),var1=sample(1:20,30,replace = T), 
             var2=sample(40:80,30,replace = T),var3=sample(110:120,30,replace = T), 
             var4 = sample(200:210,30,replace = T))
ras <- rasterFromXYZ(df)
plot(ras) # bad example but gets my point across

enter image description here

How can I specify the break points of each of these plots? For e.g. for var1 I want to specify breakpoint of 2,4,8,10,15,20. For var2, 45,60,80 and so on. I did this:

plot(ras, breaks = c(2,4,8,10,15,20))

enter image description here

But this puts the same break points for all the four raster.


Solution

  • You can do something like this.

    library(raster)
    library(viridis) # For color schemes
    
    # Create the raster brick
    ras <- rasterFromXYZ(df)
    
    # Set 4 figures arranged in 2 rows and 2 columns
    par(mfrow = c(2, 2))
    
    # Plot var1
    plot(ras$var1, breaks = c(2, 4, 8, 10, 15, 20), col = viridis(5))
    
    # Plot var2
    plot(ras$var2, breaks = c(45, 60, 80), col = viridis(2))
    
    # Plot var3
    plot(ras$var3, breaks = c(110, 113, 116, 120), col = viridis(3))
    
    # Plot var4
    plot(ras$var4, breaks = c(200, 201, 202, 204, 206, 208, 210), col = viridis(6))
    

    enter image description here