Legend of a raster map with categorical data

十年热恋 提交于 2019-11-26 18:17:16

问题


I would like to plot a raster containing 4 different values (1) with a categorical text legend describing the categories such as 2 but with colour boxes:

I've tried using legend such as :

legend( 1,-20,legend = c("land","ocean/lake", "rivers","water bodies")) 

but I don't know how to associate one value to the displayed color. Is there a way to retrieve the colour displayed with 'plot' and to use it in the legend?


回答1:


The rasterVis package includes a Raster method for levelplot(), which plots categorical variables, and produces an appropriate legend:

library(raster) library(rasterVis)  ## Example data r <- raster(ncol=4, nrow=2) r[] <- sample(1:4, size=ncell(r), replace=TRUE) r <- as.factor(r)  ## Add a landcover column to the Raster Attribute Table rat <- levels(r)[[1]] rat[["landcover"]] <- c("land","ocean/lake", "rivers","water bodies") levels(r) <- rat  ## Plot levelplot(r, col.regions=rev(terrain.colors(4)), xlab="", ylab="") 




回答2:


By default, the colours used in a raster-plot are generated by rev(terrain.colors()) (see ?raster::plot). You can use this to re-create that sequence of 4 colours for your legend - or choose a random sequence of colours:

my_col = rev(terrain.colors(n = 4)) # my_col = c('beige','red','green','blue') 

First plot the map using the colour sequence. legend = FALSE gets rid of the standard colour bar:

plot(my_raster, legend = FALSE, col = my_col) 

Add a custom legend to the bottom left. Use the fill argument to generate coloured boxes:

legend(x='bottomleft', legend = c("land", "ocean/lake", "rivers", "water bodies"), fill = my_col) 


来源:https://stackoverflow.com/questions/19136330/legend-of-a-raster-map-with-categorical-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!