How to plot out of bound raster color scale with a specific color in image R?

593 Views Asked by At

I have a raster and I want to plot the out of bound color with a specific color in image plot. The code I have so far

## read the libraries
library(raster)
library(fields)
library(grDevices)


##random raster object
set.seed(1)
r <- raster(ncol=5, nrow=5)
r[] <- rnorm(n=ncell(r),mean=2)

par(mfrow=c(2,1))
col = colorRampPalette(c("darkred","red","lightskyblue","blue","blue4"))(20)
##plot without any z limit
image(r, xaxs="i", yaxs="i", col= rev(col))
##plot with z limit
image(r, xaxs="i", yaxs="i", col= rev(col),zlim = c(min(r@data@values),2))

It looks like this

enter image description here

The first plot is a normal image plot without specifying any limits and the second plot with some limiting condition. I want to change the white color (out of bound values i.e. raster values higher than 2) in my second plot with the first color of color palette ("darkred").

Thanks.

1

There are 1 best solutions below

2
On

You can use custom breaks with the image function to set the range of the highest display color group.

set.seed(1)
r <- raster(ncol=5, nrow=5)
r[] <- rnorm(n=ncell(r),mean=2)
par(mfrow=c(2,1))
col = colorRampPalette(c("darkred","red","lightskyblue","blue","blue4"))(20)
col = rev(col)

image(r, xaxs="i", yaxs="i", col = col, main="Initial")

breaks = seq(r@data@min, r@data@max, length.out=21)    
col[which(breaks[1:20] >= 2)] = col[20]
image(r, xaxs="i", yaxs="i", col = col, breaks=breaks, main="Z-Limit")