Out of bound colour scale plot in raster

285 Views Asked by At

I have a raster and I want to plot it using image(). So far, I plotted the raster with my own color scale col.

## 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)

col = colorRampPalette(c("darkred","red","lightskyblue","blue","blue4"))(20)
image(r, xaxs="i", yaxs="i", col= rev(col))

This looks like

image.

Now, I want to plot the all the values higher than the value 2 as "darkred" (initial color from my color scale)

I found a similar post and tried the same

zlim=2
newcol = ifelse(raster(r) >= zlim,"darkred",col)
image(r, xaxs="i", yaxs="i", col= newcol)

However, I got some error message. It would be helpful if anyone can help me with this.

1

There are 1 best solutions below

0
On

Mmh... unless you really understand how col works, I wouldn't start playing with it as you try to do (you actually intend to change the color scale you use, and might end up with non-intended results).

BTW, you error probably comes from using raster(r) >= zlim instead of r[] >= zlim (but as mentioned, even with this corrected, your result wouldn't be correct).

I seems easier and more transparent to me to instead plot a new raster on top of the initial one (add=True) with a single value above the threshold (here, 1 where the raster is >=2) and a defined color (here, yellow to make it visible but you can adapt) and NA elsewhere (so that the original raster is visible by transparency):

library(raster)

# Your example
set.seed(1)
r <- raster(ncol=5, nrow=5)
r[] <- rnorm(n=ncell(r),mean=2)
col = colorRampPalette(c("darkred","red","lightskyblue","blue","blue4"))(20)
par(mfrow = c(1,2))
image(r, xaxs="i", yaxs="i", col= rev(col), main='Original')

# build a new raster with 1 where r>=2 and NA elsewhere
newr = r
newr[] = ifelse(newr[] >= 2, 1, NA)
image(r, xaxs="i", yaxs="i", col= rev(col), main='Vals >=2 in yellow')
image(newr, col= "yellow", add=T)

enter image description here