绘制栅格,使其色带偏差在零附近 [英] Plotting a raster with the color ramp diverging around zero
问题描述
我正在尝试绘制具有正值和负值的地图.
I am trying to plot a map with positive and negative values.
所有正值都应为红色,负值应为蓝色,零应为白色,就像此示例图中的离散颜色一样
All positive values should have red color while negative should have blue color and zero should have white just like in this sample plot with discrete colors
以下是我正在使用的代码:
Below is the code I'm using:
library (rasterVis)
ras1 <- raster(nrow=10,ncol=10)
set.seed(1)
ras1[] <- rchisq(df=10,n=10*10)
ras2=ras1*(-1)/2
s <- stack(ras1,ras2)
levelplot(s,par.settings=RdBuTheme())
非常感谢您提供了可以在其他映射练习中应用的通用解决方案.
Thanks very much for providing a general solution which can be applied in other mapping exercises as well.
推荐答案
我写了要点去做这个.它采用由rasterVis::levelplot
生成的trellis
对象和色带,并绘制颜色在零附近发散的对象.
I wrote a gist to do this. It takes a trellis
object generated by rasterVis::levelplot
, and a colour ramp, and plots the object with the colours diverging around zero.
使用您的s
,您可以像这样使用它:
Using your s
, you can use it like this:
devtools::source_gist('306e4b7e69c87b1826db')
p <- levelplot(s)
diverge0(p, ramp='RdBu')
ramp
应该是RColorBrewer
调色板的名称,要插值的颜色矢量或colorRampPalette
.
ramp
should be the name of a RColorBrewer
palette, a vector of colours to be interpolated, or a colorRampPalette
.
以下是来源:
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$par.settings$regions$col <- ramp(1000)[zlim[-length(zlim)]]
p
}
请注意,正如@LucasFortini的帖子中所建议的那样,如果您乐意拥有colorkey在零以上和以下延伸相同的距离,例如:levelplot(s,par.settings=RdBuTheme(), at=seq(-max(abs(cellStats(s, range))), max(abs(cellStats(s, range))), len=100))
.
Note that, as suggested in @LucasFortini's post, the process is much simpler if you're happy to have the colorkey extend the same distance above and below zero, e.g.: levelplot(s,par.settings=RdBuTheme(), at=seq(-max(abs(cellStats(s, range))), max(abs(cellStats(s, range))), len=100))
.
这篇关于绘制栅格,使其色带偏差在零附近的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!