code123 code123 - 1 year ago 76
R Question

Match color with numbers Raster Map R

I would like to match color to raster class. Assume I have the following colors and these rasters:

library(rasterVis)
mycolors=c("darkred","red3", "orange", "yellow", "lightskyblue",
"royalblue3","darkblue")
s <- stack(replicate(6, raster(matrix(runif(100), 10))))
levelplot(s, layout=c(3, 2), col.regions=mycolors, index.cond=list(c(1, 3, 5, 2, 4, 6)))


I would like to classify the rasters in "s" such that values from 0 to 0.1 are colored in "darkred" and values from 0.9 to 1 are colored in "darkblue". Basically, I would like to classify my data to "n" classes and then assign each class to a color of my choice.

Finally,the colorkey should have as labels the various raster classes. Some insights are found here 1 and 2

Answer Source

You have to convert each layer to a factor with ratify using the cut function to define the breaks.

library(rasterVis)

s <- stack(replicate(6,
                     raster(matrix(runif(100), 10))))

brks <- seq(0, 1, .1)
## These are the labels to be included as levels in the RAT
labs <- levels(cut(s[], brks))

## Auxiliary function to convert each layer to a factor.
makeFactor <- function(r){
    r <- ratify(cut(r, brks))
    rat <- levels(r)[[1]]
    rat$int <- labs
    levels(r)[[1]] <- rat
    r
}

lFactor <- lapply(seq_len(nlayers(s)),
                  FUN = function(i) makeFactor(s[[i]]))
sFactor <- stack(lFactor)

Now choose your favorite colors and you are done.

levelplot(sFactor, col.regions = mycolors)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download