简体   繁体   English

具有分类数据的栅格地图图例

[英]Legend of a raster map with categorical data

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:我想绘制一个包含 4 个不同值 ( 1 ) 的栅格,其中包含描述类别的分类文本图例,例如2但带有颜色框:

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?有没有办法检索用“绘图”显示的颜色并在图例中使用它?

初始栅格

带有图例的光栅

The rasterVis package includes a Raster method for levelplot() , which plots categorical variables and produces an appropriate legend: rasterVis包包含一个用于levelplot()Raster方法,该方法绘制分类变量并生成适当的图例:

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="")

在此处输入图片说明

By default, the colours used in a raster-plot are generated by rev(terrain.colors()) (see ?raster::plot ).默认情况下,栅格图中使用的颜色由rev(terrain.colors()) (请参阅?raster::plot )。 You can use this to re-create that sequence of 4 colours for your legend - or choose a random sequence of colours:您可以使用它为您的图例重新创建 4 种颜色的序列 - 或选择随机的颜色序列:

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: legend = FALSE去掉了标准颜色条:

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

Add a custom legend to the bottom left.在左下角添加自定义图例。 Use the fill argument to generate coloured boxes:使用fill参数生成彩色框:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM