code123
code123

Reputation: 2156

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

Upvotes: 1

Views: 464

Answers (1)

Oscar Perpi&#241;&#225;n
Oscar Perpi&#241;&#225;n

Reputation: 4511

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)

Upvotes: 2

Related Questions