Search code examples
rplotraster

Change colour scale R


I am printing a raster r created from matrix m with the following code

r <- t(raster(m))
extent(r) <- c(-180, 180, -90, 90)
setcol <- unlist(m)
setcol[is.na(setcol)] <- 0
length_val<-floor(max(setcol) - min((setcol)))
colorscale <- colorRampPalette(c("blue","green","yellow","red"), space="Lab")(length_val)
x.scale <- list(cex=1.5,font=2) 
y.scale <- list(cex=1.5,font=2)

graph <- levelplot(r, margin=FALSE ,xlab=list("",cex=1.5),ylab=list("",cex=1.5),main = list(title,cex=2),col.regions=colorscale,
                   colorkey=list(labels=list(cex=1)),
                   panel = function(x, y, ...) {
                   panel.levelplot(x, y,  ...)
                   mp <- map("world", plot = FALSE, fill=FALSE,interior = FALSE)
                   lpolygon(mp$x, mp$y, fill=FALSE, col="white")},
                   scales=list(x=x.scale, y=y.scale)
)
print(graph)

What I get is a very spread colour scale (I can't post any image) but what I would like instead is a color scale with more colours around the middle values and just one or two colours for the extreme values..

Can anyone help me?

Many thanks


Solution

  • I do exactly that in my code. I use rainbow function, and in the start and end argument (within 0..1) I specify the desired interval for each group of values:

    colors <- c(rainbow(length(levels) - 14, start = 0.78, end = 0.8, s = 0.5),
                rainbow(14,                  start = 0.45, end = 0.75))
    

    This way I can, for the 14 most important values, assign much bigger range of colors so that they can be easily distinguished.