Search code examples
rmapsrasterlevelplot

Use a single colour for range of values and include inequality symbol on colorkey levelplot R


I have 4 rasters with values spanning both positive and negative scales. For the 4 rasters: 1) I will like to use just one color break on both ends of the colorkey for all values outside the range +/-20, say. This is because I am more interested in the intra-raster and inter-raster variability of smaller values.

2) How can I specify the labels of the colorkey such that they look similar to: at=c(<=-20, -10, 0 , 10 , >=20). The most important thing here is how to include the inequality sign in the colorkey label

Reproducible example and sample code shown below. The image shows my actual data display using levelplot function.

library(raster)
library (colorRamps)
set.seed(100)
ras <- raster(ncol=100, nrow=100)
ras1 <- setValues(ras, (1:ncell(ras))/100 + rnorm(ncell(ras)) - 50)

s=stack(ras1,ras1,ras1,ras1)


color_levels=14 #the number of colors to use
max_abolute_value=max(abs(c(cellStats(s, min), cellStats(s, max)))) #what is the maximum absolute value of raster?
color_sequence=unique(round(seq(-max_abolute_value,max_abolute_value,length.out=color_levels+1),0))

myColorkey <- list(at=color_sequence,space = "bottom", ## where the colors change 
                   labels=list(axis.line = list(col = NA),at=color_sequence,rot=0,cex=0.9,font=6,
                               fontface=1),height=1,width=1.4)

col1 <- colorRampPalette(c("darkred", "red3","red",
                           "gray96",  "lightskyblue", "royalblue3", 
                           "darkblue"))

levelplot(s,contour=F, layout=c(4, 3),  col.regions = col1,colorkey=myColorkey,margin=FALSE,xlab=NULL,ylab=NULL,par.strip.text=list(cex=0))

Solution

  • As for (i), you could simply reclassify the raster layers and set all values smaller than -20 (or larger than 20) e.g. to -20.5 (or 20.5). I guess this makes sence since you are not interested in smaller or larger values anyway. As for (ii), I would recommend using spplot and modify the colorkey as detailed in ?levelplot (from package lattice). Note that the desired labels can easily be inserted using Unicode characters (e.g., greater than or equal to).

     ## reclassify data
    m_rcl <- matrix(c(-100, -20, -20.5, 
                      20, 100, 20.5), 
                    byrow = TRUE, ncol = 3)
    
    s_rcl <- reclassify(s, m_rcl)
    
    ## colors
    library(RColorBrewer)
    cols <- brewer.pal(6, "RdBu")
    cols <- rev(cols)
    cols <- colorRampPalette(cols)
    
    ## display data
    spplot(s_rcl, col.regions = cols(100), at = seq(-21, 21, 1),
           colorkey = list(space = "bottom", 
                           labels = list(at = seq(-20, 20, 10), 
                                         labels = c("\u2264 -20", 10, 0, 10, "\u2265 20"))))
    

    spplot