[R] divergent colors around zero in levelplot()

Achim Zeileis Achim.Zeileis at uibk.ac.at
Sat Nov 23 10:47:18 CET 2013

On Fri, 22 Nov 2013, Don McKenzie wrote:

> I would like to produce a levelplot with divergent colors such that increasingly negative values of Z get darker in the first color and increasingly
> positive values get darker in the second color.  this is common in cartography. I have tried tinkering with the col.regions argument but the best I can do
> is to get the split in the middle of my range of Z, but in my particular case range(Z) is (-1,12).
> I am using R 3.0.2 on OSX 10.9
> Here is an example
> x <- y <- c(1:25)
> grid <- expand.grid(x=x,y=y)
> grid$z <- sort(runif(625,min=-1,max=12))
> levelplot(z ~ x*y,grid)   # produces the default pink and blue but the split is at ~5.5
> # do something clever here
> # e.g., my.colors <- <create a palette that splits at zero>
> levelplot(z ~ x*y,grid,col.regions=my.colors)  # so there should be some light pink at the bottom and the rest increasingly intense blue
> Ideas appreciated.  Thanks in advance.

One approach is to limit the range of colors (to match the range of the 
data) as you suggest above. The other approach is to extend the range of 
the legend (beyond the range of the data). For example:

levelplot(z ~ x*y, grid, at = seq(-12, 12, length = 100))

This produces a legend that is symmetric around zero.

For other/better diverging color palettes, you can use the RColorBrewer 
package (as suggested by Bert) or the colorspace package (see e.g., its 
graphical choose_color() tool).

> Don McKenzie
> Research Ecologist
> Pacific Wildland Fire Sciences Lab
> US Forest Service
> Affiliate Professor
> School of Environmental and Forest Sciences
> University of Washington
> dmck at uw.edu
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list