I would like to use the raster attribute table information to create the legend of a raster such as the raster 1 and display the legend only for the class displayed in the raster. I build an example to explain what I would like to get.
1/ Build the raster
r <- raster(ncol=10, nrow=10)
values(r) <-sample(1:3,ncell(r),replace=T)
2/ Add the Raster Attribute Table
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/ Plot the raster Fig 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)
I would like to replace the legend =rat$legend
parammeter by a properties of the raster linked to the ratser attribute table. I have tried different combination using levels()
such as c(levels(r)[[1]][1])
but I generate a list and not a character not usable in the legend parameter.
4/ Crop and plot the raster to a part with only 2 classes (here the 4 pixels at the down right extent) Fig 2
rcrop<-crop(r,extent(r,9,10,9,10))
plot(rcrop,col=my_col,legend=F,box=F,axes=F)
For this second fig, I thus would like to diplay automatically only the legend of the class displayed on the raster 2.
Here is the solution proposed by Roman 4.