I would like to plot a raster containing 4 different values (1) with a categorical text legend describing the categories such as 2 but with colour boxes.

I've tried using legend such as :

legend( 1,-20,legend = c("land","ocean/lake", "rivers","water bodies"))

but I don't know how to associate one value to the displayed color. Is there a way to retrieve the colour displayed with 'plot' and to use it in the legend?

Initial rasterenter image description here

Raster with legend enter image description here


You are not providing a reproducible code, so I made up a simple example that hopefully will allow you to tailor it to your needs.

r <- raster(volcano)
plot(r, legend = FALSE, col = rev(terrain.colors(4)))
legend("topright", legend = c("category 1", "category 2", "category 3", "category 4"), fill = rev(terrain.colors(4)))

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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