Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse legend in raster

Tags:

r

legend

r-raster

While plotting a raster image, for example:

library(raster)

r <- raster(nrow = 3, ncol = 3)
values(r) <- 1:9

plot(r, col = terrain.colors(255))

enter image description here

How can I get the legend being in ascending order, i.e. from 1 (top) to 9 (bottom)?

I thought of the legend.args, but couldn't find the right arguments.

like image 603
schosse-sitzer Avatar asked Dec 30 '25 01:12

schosse-sitzer


1 Answers

I tried a bit and I think I've found a solution myself, even though it is not the most elegant way.

library(raster)

r <- raster(nrow = 3, ncol = 3)
values(r) <- 1:9

par(mar = c(3, 3, 4, 3))
plot(r, col = terrain.colors(255),legend = FALSE, xlim = c(-200,200),
    ylim = c(-200,200))

vz = matrix(1:100, nrow = 1)
vx = c(185, 195)
vy = seq(-10, 10, length.out = 100)

par(new = TRUE, mar = c(3, 3, 4, 3))
plot(1, xlab = "", ylab = "", axes = FALSE, type = "n",
    xlim = c(-200, 180), ylim = c(-20, 20))
image(vx, vy, vz, col = rev(terrain.colors(255)), axes = FALSE, 
    xlab = "", ylab = "", add = TRUE)
polygon(c(185, 195, 195, 185), c(-10, -10, 10, 10))
axis(4, at = seq(-10, 10, length.out = 9), labels = 9:1, las = 1)

enter image description here

Anyway, I'd appreciate other ideas!

like image 94
schosse-sitzer Avatar answered Jan 01 '26 13:01

schosse-sitzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!