[GIS] Using a fixed palette range to plot an NDVI raster in R

colorcolor rampndvirraster

I would like to plot an NDVI raster with rasterVis packages using the normalized colors from red to green. I don't understand how fix the color scale from 0 to 1 even if my raster value are between 0.15 and 0.40

I have tried :

library(rasterVis)

n <- 1000
col.seq <- seq(0.0001, 1, length.out=n)
brks <- c(0, col.seq, Inf)
cuts <- cut(as.matrix(stackmean), breaks = brks)
colors <- colorRampPalette(c("red", "yellow", "lightgreen"))(length(levels(cuts))-1)

levelplot(stackmean, col.regions=colors)

enter image description here
My scale clearly doesn't work !

Best Answer

You need to supply levelplot() with a bit more information, via its at= argument, so that it can know the set of intervals to which you want the colors in col.regions applied.

library(rasterVis)

## A raster with values between 0.15 and 0.40
r <- raster(matrix(runif(400, min = 0.15, max = 0.4), ncol = 20))

## Set up color gradient with 100 values between 0.0 and 1.0
breaks <- seq(0, 1, by = 0.01)
cols <- colorRampPalette(c("red", "yellow", "lightgreen"))(length(breaks) - 1)

## Use `at` and `col.regions` arguments to set the color scheme
levelplot(r, at = breaks, col.regions = cols)

enter image description here