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
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.
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 ofr[] >= 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):