Skip to content

Instantly share code, notes, and snippets.

@Pakillo
Forked from johnbaums/diverge0.R
Created December 12, 2019 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pakillo/4da944d03d688d56ee34bbf174aea26f to your computer and use it in GitHub Desktop.
Save Pakillo/4da944d03d688d56ee34bbf174aea26f to your computer and use it in GitHub Desktop.
Plot a rasterVis::levelplot with a colour ramp diverging around zero
diverge0 <- function(p, ramp) {
# p: a trellis object resulting from rasterVis::levelplot
# ramp: the name of an RColorBrewer palette (as character), a character
# vector of colour names to interpolate, or a colorRampPalette.
require(RColorBrewer)
require(rasterVis)
if(length(ramp)==1 && is.character(ramp) && ramp %in%
row.names(brewer.pal.info)) {
ramp <- suppressWarnings(colorRampPalette(brewer.pal(11, ramp)))
} else if(length(ramp) > 1 && is.character(ramp) && all(ramp %in% colors())) {
ramp <- colorRampPalette(ramp)
} else if(!is.function(ramp))
stop('ramp should be either the name of a RColorBrewer palette, ',
'a vector of colours to be interpolated, or a colorRampPalette.')
rng <- range(p$legend[[1]]$args$key$at)
s <- seq(-max(abs(rng)), max(abs(rng)), len=1001)
i <- findInterval(rng[which.min(abs(rng))], s)
zlim <- switch(which.min(abs(rng)), `1`=i:(1000+1), `2`=1:(i+1))
p$legend[[1]]$args$key$at <- s[zlim]
p[[grep('^legend', names(p))]][[1]]$args$key$col <- ramp(1000)[zlim[-length(zlim)]]
p$panel.args.common$col.regions <- ramp(1000)[zlim[-length(zlim)]]
p
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment