I have a raster in .tif format which I am trying to visualize in R using levelplot. Here is what I have done so far:
library(raster)
library(lattice)
data_tif <- raster("fthrt14_21.tif", RAT = TRUE)
data_tif
rat <- read.dbf("fthrt14_21.tif.vat.dbf")
rat
data_tif <- ratify(data_tif)
colnames(rat)[1] <- "ID"
levels(data_tif) <- rat
levelplot(data_tif, col.regions=rev(terrain.colors(5)),main = "Fire Threats"
, attr(THRT_CLASS))
I am getting an error: Error in UseMethod("levelplot") : no applicable method for 'levelplot' applied to an object of class "c('RasterLayer', 'Raster', 'BasicRaster')"
How can I resolve this error? This is what my RAT looks like:
# Code for getting reproducible example of RAT file
Value <- c(1,2,3,4,5)
Count <- c(15918472,127852558,102695341,108155367,8927377)
THRT_CLASS <- c("Low","Moderate","High","Very High","Extreme")
RAT <- data.frame(Value,Count,THRT_CLASS
Well, this is a bit tricky! First thing is loading raster
and lattice
libraries and then using lattice::levelplot
for plotting categorical raster. However, you should be using rasterVis::levelplot
for this purpose.
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
rasterVis::levelplot(r, col.regions=rev(terrain.colors(4)), xlab="", ylab="")
then you get this plot:
However, if you use below script you bump into error message:
> levelplot(r, col.regions=rev(terrain.colors(4)), xlab="", ylab="")
Error in UseMethod("levelplot") : no applicable method for 'levelplot' applied to an object of class "c('RasterLayer', 'Raster', 'BasicRaster')"
Note that even if you only load raster
package (not lattice
), you may still see this error as the lattice
and rasterVis
share same function levelplot
and raster
package automatically loads lattice
. To get around this use rasterVis::levelplot
.