我想使用栅格属性表信息来创建栅格的图例,例如栅格1 https://i.stack.imgur.com/tgC2P.png并仅显示栅格中显示的类的图例。我举了一个例子来解释我想要得到什么。
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/ 绘制栅格 Fig 1 https://i.stack.imgur.com/tgC2P.png
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)
我想更换legend =rat$legend
参数由链接到栅格属性表的栅格属性决定。我尝试过使用不同的组合levels()
例如c(levels(r)[[1]][1])
但我生成一个列表,而不是在图例参数中不可用的字符。
4/ 将栅格裁剪并绘制到仅包含 2 个类别的部分(此处为右下范围的 4 个像素) Fig 2 https://i.stack.imgur.com/VzF8M.png
rcrop<-crop(r,extent(r,9,10,9,10))
plot(rcrop,col=my_col,legend=F,box=F,axes=F)
对于第二个图,我想仅自动显示光栅上显示的类的图例2 https://i.stack.imgur.com/VzF8M.png.
Here is the solution proposed by Roman 4 https://i.stack.imgur.com/hAJdN.png.