rterra

Modify contents of the legend in terra::plot()


Given:

f <- system.file("ex/elev.tif", package="terra") 
r <- rast(f)
d <- classify(r, c(100,200,300,400,500))
plot(d, type="classes",col=c("grey","red","cyan","yellow"))

enter image description here

is there a way to modify the contents of the legend? for example, to be A,B,C,D instead of the intervals.


Solution

  • If it is only for plotting, you can use argument "levels" like this:

    library(terra)
    r <- rast(system.file("ex/elev.tif", package="terra") )
    d <- classify(r, c(100,200,300,400,500))
    plot(d, type="classes",col=c("grey","red","cyan","yellow"), 
            levels=c("A", "B", "C", "D"))
    

    enter image description here

    For a more general solution you could do

    levels(d) <- cbind(levels(d)[[1]], category=c("A", "B", "C", "D"))
    activeCat(d) <- 2
    plot(d)