Search code examples
rgraphicsrasterspatstat

Customize breaks on a color gradient legend using base R


Here is a sample script using random numbers instead of real elevation data.

library(gridExtra)
library(spatstat) #im function

elevation <- runif(500, 0, 10)
B <- matrix(elevation, nrow = 20, ncol = 25)
Elevation_Map <- im(B)
custom <- colorRampPalette(c("cyan","green", "yellow", "orange", "red"))
plot(Elevation_Map, col = custom(10), main = NULL)

This is the plot and legend that I get:

enter image description here

This is the legend that I am trying to recreate in R (this one made in Word):

enter image description here

I know this is possible and its probably a simple solution but I've tried using some examples I found online to no avail.

This plot (with real elevation data) is an art piece that will be hung in a gallery, with the elevation plot on 1 board and the legend on a separate board. I tried to get R to plot just the plot without the legend using

plot(Elevation_Map, col = custom(10), main = NULL, legend = NULL)

like I have in the past but for some reason it always plots the legend with the plot. As of right now I'm planning on just cropping the .pdf into 2 separate files to achieve this.


Solution

  • The code in the original post is using the im class from the spatstat package. The plot command is dispatched to plot.im. Simply look at help(plot.im) to figure out how to control the colour ribbon. The relevant argument is ribargs. Here is a solution:

    plot(Elevation_Map, col=custom(10), main="",
         ribargs=list(at=Elevation_Map$yrange, 
                      labels=c("Low Elevation", "High Elevation"),
                      las=1))