For example, I have a landcover raster and I want to use terra::plot to make a map.

test <- rast('test.tif')

enter image description here

The order now is "3,4,6,8". Now I want to reorder it to "3,4,8,6"

How can I do this?

1 Answer 1


You do not include example data/code, but I am assuming this is a categorical raster. Something like this:

r <- rast(nrows=10, ncols=10)
values(r) <- sample(3, ncell(r), replace=TRUE)
levels(r) <- data.frame(id=1:3, cover=c("forest", "water", "urban"))

The categories follow the order of the IDs in the attribute table (unless you do plot(r, sort=TRUE)). It was not easy to change that, but with terra version 1.5.39 (currently the development version) you can now use the sort argument to change the order

plot(r, sort=c( "water", "urban", "forest"))

You can install the development version with install.packages('terra', repos='https://rspatial.r-universe.dev')

See here for SpatVector

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.