Search code examples
rqmlr-rasterlevelplotrastervis

levelplot plots the wrong categorical colours


I have received a .tif file alongside a .qml file containing information about the colour for each value (e.g. forest is green, clouds are black).

library(raster)
library(rasterVis)

sm <- raster("UT_classification_coded.tif")

########## Classify raster / build attribute table
    sm <- ratify(sm)
    rat_sm <-levels(sm)[[1]]
    # Create categories
    rat_sm$landcover <- c('Forest', 'Active vegetation', 'Senescent vegetation', 'Disturbed', 'Rice flooded', 'Rice growing', 'Settlement', 'Water', 'Cloud', 'Cloud shadow', 'Forest') 
    levels(sm) <- rat_sm




##### plot the colours using the .qml file
     levelplot(sm, col.regions=c("#00b144", "#00ff00", "#ffc0a0", "#00ebeb", "#86b1ec", "#de57ff", "#ffff00", "#0000ff", "#000000", "#000000", "#008000"), xlab=NULL, ylab=NULL, scales=list(draw=FALSE), maxpixels=6e6)

The problem is that levelplot "believes" that the land use categories (Forest, rice flooded etc.) are in the reverse alphabetical order, and so are the colours. Thus the colours are assigned to the wrong category. For example, the last three colours ("#000000", "#000000", "#008000") are assigned to the Water, Settlement, Scenecent vegetation.

Grateful for any suggestions on a way to fix this (aside from plotting the colours in the reverse alphabetical order, which is tedious because that's not how the .qml file presents the information).

EDIT: here's the description of the .tif file

class       : RasterLayer 
dimensions  : 10981, 10981, 120582361  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 299993, 409803, 9190235, 9300045  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=18 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0 
data source : C:\Users\Documents\UT_classification_coded.tif 
names       : UT_classification_coded 
values      : 1, 15  (min, max)

Solution

  • I have committed changes in the code to solve this issue. Please, try the development version of the package:

    ## install.packages('remotes')
    remotes::install_github('oscarperpinan/rasterVis')