[英]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)
此外,我已经对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)
也许查询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.