簡體   English   中英

如何直接使用柵格屬性表來渲染柵格,並僅為柵格中顯示的類顯示圖例?

[英]How to legend a raster using directly the raster attribute table and displaying the legend only for class displayed in the raster?

我想使用柵格屬性表信息來創建柵格的圖例,例如柵格1,並僅為柵格中顯示的類顯示圖例。 我建立了一個例子來解釋我想要得到什么。

1 /構建柵格

r <- raster(ncol=10, nrow=10)
values(r) <-sample(1:3,ncell(r),replace=T)

2 /添加柵格屬性表

r <- ratify(r) # build the Raster Attibute table
rat <- levels(r)[[1]]#get the values of the unique cell frot the attribute table
rat$legend <- c('Class A', 'Class B', 'Class C')
levels(r) <- rat

3 /繪制光柵1

my_col=c('blue','red','green')
plot(r,col=my_col,legend=F,box=F,axes=F)
legend(x='top', legend =rat$legend,fill = my_col)

我想用鏈接到ratser屬性表的柵格的屬性替換legend =rat$legend parammeter。 我嘗試了使用levels()不同組合,例如c(levels(r)[[1]][1])但是我生成了一個列表而不是在legend參數中不可用的字符。

4 /裁剪並將光柵繪制到只有2個類的部分(這里是右下角的4個像素)2

rcrop<-crop(r,extent(r,9,10,9,10))
plot(rcrop,col=my_col,legend=F,box=F,axes=F)

對於第二個圖,我因此想自動只顯示光柵2上顯示的類的圖例。

傳說中的光柵

帶有圖例的裁剪光柵


這是Roman 4提出的解決方案。 羅馬提出的解決方案

如果您願意使用lattice圖形, rasterVis 包中定義的levelplot方法可以顯示帶有基於RAT的圖例的分類數據:

library(raster)
library(rasterVis)

r <- raster(ncol=10, nrow=10)
values(r) <- rep(1:4, each=25)

r <- ratify(r) 
rat <- levels(r)[[1]]
rat$legend <- c('Class A', 'Class B', 'Class C', 'Class D')
levels(r) <- rat

levelplot(r)

rat.png

此外,我已經對GitHub提供開發版本進行了一些更改 ,以管理RAT Raster*其RAT級別並非全部存在於數據中:

rcrop <- crop(r,extent(r,6,10,1,10))
levelplot(rcrop)

大鼠作物

rcrop <- crop(r,extent(r,1,5,1,10))
levelplot(rcrop)

大鼠作物2

也許查詢rcrop柵格以找出裁剪柵格中的哪些級別並將其傳遞給圖例?

legend(x = 'top', legend = unique(getValues(rcrop)), fill = my_col)

謝謝。 根據你的建議,我找到了一個解決方案:

plot(rcrop,col=my_col[unique(getValues(rcrop))],legend=F,box=F,axes=F)
legend_full<-data.frame(levels(rcrop))
legend(x='top', legend =as.character(unlist(legend_full[unique(getValues(rcrop)),2])),fill = my_col[unique(getValues(rcrop))])

它工作並允許獨立於柵格中顯示的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM