Legend of a raster map with categorical data

后端 未结 2 2072
庸人自扰
庸人自扰 2020-12-03 03:57

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

2条回答
  •  一向
    一向 (楼主)
    2020-12-03 04:38

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

    enter image description here

提交回复
热议问题