如何为 rasterStack 中的所有栅格图层显示相同的图例 [英] How to display the same legend for all raster layers in a rasterStack
问题描述
我已经浏览了所有 SO,但无法找到这个特定问题的答案:
I've looked through all SO but haven't been able to find an answer to this specific question:
我有一个包含多个层的 rasterStack,其值跨越了相当大的范围.知道每一层的值和选择的色标我相信我已经设法用相同的色标绘制所有栅格,但我现在面临三个问题:
I have a rasterStack with several layers whose values span over a quite large range. Knowing the values of each layer and the chosen colour scale I believe I have managed to plot all the rasters with the same colour scale, but I face three problems now:
- 我无法确定这些值是否使用相同的色标绘制,尽管看起来是这样
- 我无法为所有图层绘制相同的比例和比例标签.
我在 ras3 中的一个单元格ras3[3,9]
没有着色,但它不是 NA!
- I can't be sure that the values are being plotted with the same colour scale, although it seems like it
- I can't manage to plot the same scale and scale labels for all layers.
One of my cells in ras3,ras3[3,9]
, doesn't get coloured, but it is not NA!
示例脚本如下:
library(raster)
# generate example rasters
set.seed(123)
ras1 <- raster(ncol = 10, nrow= 10)
values(ras1) <- runif(100, 1, 10)
ras2 <- raster(ncol = 10, nrow = 10)
values(ras2) <- runif(100, 5, 50)
ras3 <- raster(ncol = 10, nrow = 10)
values(ras3) <- runif(100, 10, 100)
# stack them
rasStack <- stack(ras1, ras2, ras3)
# plot normally to check the values
plot(rasStack)
# obtain max and min values
maxv <- max(maxValue(rasStack))+1
minv <- min(minValue(rasStack))
# set the breaks between min and max values
brks <- seq(minv,maxv,by=0.1)
nbrks <- length(brks)-1
r.range <- c(minv, maxv)
# generate palette
colfunc<-colorRampPalette(c("springgreen", "royalblue", "yellow", "red"))
# plot in a loop with a common legend, using legend.only = T
for(i in seq_len(nlayers(rasStack))){
tmp <- rasStack[[i]]
plot(tmp, breaks=brks,col=colfunc(nbrks), legend = F, zlim=c(minv,maxv),
main = names(tmp))
plot(tmp, legend.only=TRUE, col=colfunc(nbrks),
legend.width=1, legend.shrink=0.75,
axis.args=list(at=seq(minv, maxv, 5),
labels=round(seq(r.range[1], r.range[2], 5), 2),
cex.axis=0.6),
legend.args=list(text='value', side=4, font=2, line=2.5, cex=0.8))}
# check that the blank cell has a valid value
ras3[3, 9]
> 99.01704
任何帮助将不胜感激!
根据 ycw 的回答,我已经编辑了代码,现在问题没有了.3消失了!
as per ycw's answer I've edited the code and now problem no. 3 has disappeared!
推荐答案
最后一个中断号应该大于你数据的最大值(maxv
),这样最大值的单元格就可以根据最后一个颜色类别着色.否则,单元格将为空白.
The last break number should be larger than the maximum value of your data (maxv
) so that the cell with the maximum can be colored based on the last color category. Otherwise, the cell will be blank.
我通过更改 maxv <- max(maxValue(rasStack)) + 1
修改了您的代码,但没有更改其他部分.结果看起来不错.
I modified your code by changing maxv <- max(maxValue(rasStack)) + 1
but did not change other parts. The result looks good.
这篇关于如何为 rasterStack 中的所有栅格图层显示相同的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!