Legend of a Raster Map with Categorical Data

Legend of a raster map with categorical data

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

Sample Image

Short legend height in rastervis plot of categorical raster

You can set the legend height by passing colorkey=list(height=1) to the levelplot function.

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, colorkey=list(height=1), col.regions=rev(terrain.colors(4)), xlab="", ylab="")

How to legend a raster using directly the raster attribute table and displaying the legend only for class displayed in the raster?

If you are willing to use lattice graphics, the levelplot method
defined in the rasterVis
package is able to
display categorical data with a legend based on the 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)

rat.png

Besides, I have
commited some changes
in the
development version available at GitHub
to manage a Raster* whose RAT levels are not all present in the
data:

rcrop <- crop(r,extent(r,6,10,1,10))
levelplot(rcrop)

rat crop

rcrop <- crop(r,extent(r,1,5,1,10))
levelplot(rcrop)

rat crop2

How to ssplot or ggplot a categorical raster

As I said in commentaries: reclassify, add raster attribute table and plot with levelplot():

library(raster)

# Reproducible example
r <- raster()
r[] <- runif(ncell(r), min = 0, max = 2)

# Reclassify
r <- reclassify(r, c(0, 0.5, 1,
0.5, 1, 2,
1, 1.5, 3,
1.5,Inf,4))

# View
plot(r)

Sample Image

# Values as factor
r <- as.factor(r)
# Extract attribute table
rat <- levels(r)[[1]]
# Set custom breaks
rat[["zn"]] <- c("low", "medium", "high", "very high")
# Add back RAT
levels(r) <- rat

# Plot
rasterVis::levelplot(r)

Sample Image



Related Topics



Leave a reply



Submit