【发布时间】:2019-08-05 21:54:32
【问题描述】:
我正在使用 rasterVis 包中的 R 函数 levelplot() 绘制具有单个发散色带的三个栅格的堆栈。我想更改光栅色带的比例,以便地图突出较低值的差异。这可以通过颜色中断的非线性分箱来完成。
我正在使用@jbaums 编写的a gist 的代码(代码包含在下面)。关于如何在此代码中调整色带以使中断遵循 2^x 但保留最小值和最大值的任何建议?似乎更改s(下)的序列会产生预期的效果。
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
}
下面是一些应用此功能的代码:
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)
p <- levelplot(s, par.settings=RdBuTheme())
diverge0(p, ramp='RdBu')
【问题讨论】:
-
如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。提供一些实际调用此函数的示例代码,以显示您期望的输出。
-
听起来您需要将您的连续字段值
cut()转换为因子向量(箱)。我已经用raster对象做了相当多的事情,然后将它们传送到ggplot。例如:as.data.frame(my_raster, xy = TRUE) %>% ggplot(aes(x,y, fill = cut_bins)) + geom_raster() + scale_fill_manual() + theme_void().然后在scale_fill_manual中为每个 bin 指定值、中断和标签。完全控制!
标签: r raster levelplot rastervis