Kent Johnson
Kent Johnson

Reputation: 3388

How can I reverse the y-axis in a raster plot?

I would like to plot a raster with the y-axis increasing from top to bottom, and the raster correspondingly flipped. Is there a way to do this? Specifying ylim in decreasing order gives an error.

For example, I would like this plot with the y-axis running from -100 at the top to 100 at the bottom, with the raster also reversed to put green on top and orange on the bottom:

library(raster)
r <- raster(nrows=10, ncols=10)
r <- setValues(r, 1:ncell(r))
plot(r)


# Fails
plot(r, ylim=c(100, -100))
#> Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add, : invalid ylim

Created on 2020-10-30 by the reprex package (v0.3.0)

Upvotes: 1

Views: 783

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

The approach shown below appears to work

Example data

library(raster)
r <- raster(nrows=10, ncols=10, vals=1:100)

Flip the raster vertically, and add the horizontal axis

plot(flip(r, "y"), axes=F)
axis(1)

Get the labels for the vertical axis, and plot them in reverse order

ylabs <- axis(2, labels=FALSE, tick=FALSE)
axis(2, at=ylabs, labels=rev(ylabs))

Upvotes: 1

Related Questions