Search code examples
rasterlevelplotrastervis

Short legend height in rastervis plot of categorical raster


In plotting categorical raster maps with levelplot, such as Josh O'Brien's answer here Legend of a raster map with categorical data, the legend height always become shorter. Is there a way to adjust the legend height the same height as the plot window?


Solution

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