Search code examples
rmatrixplotraster

How to set certain values to specific colour in R?


I have one matrix r (raster). I would like to plot r , this simply can be done using

plot (r)

But I would like to mark all values of 20 (so this value will not be taken into account in the scale of legend) to red colour and plot r normally as below. a reproducible example:

library(raster)
r <- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)

This will produce this:

enter image description here


Solution

  • elegant is different but is this what you intend to do?

    par(mfrow=c(2,2))
    plot(r)
    r.20 <- calc(r, fun=function(x){ x[x == 20] <- NA; return(x)} )
    as.matrix(r.20)
    plot(r.20)
    r.not20 <- calc(r, fun=function(x){ x[x != 20] <- NA; return(x)} )
    plot(r.not20, col="red")
    plot(r.20);
    par(new=TRUE)
    plot(r.not20, col="red", legend=FALSE)
    

    enter image description here