Search code examples
rgraphraster

raster legend applies color not specified in pallette


I just do not understand why the legend does not plot on yellow,as especified in the pallette.

r  <- raster()
values(r)=sample(-5:2, ncell(r), replace=T)
pal <- colorRampPalette(c("red","yellow"))
cuts=c(-5,0,2)
plot(r)
plot(r,col=pal(length(cuts)),breaks=cuts,legend.only=TRUE, horizontal = F,
  add=T,
  smallplot=c(0.2,0.22, 0.1,0.7),
  axis.args=list(at=c(-5,0,2)), labels=c(-5,0,2))

Thanks in advance,


Solution

  • I think this is because with plot(..., breaks=cuts) you are using three cutting points to effectively create just two categories. See how to make the yellow appear on the legend:

    
    r <- raster()
    values(r) <- sample(-5:2, ncell(r), replace = T)
    pal <- colorRampPalette(c("red", "yellow"))
    cuts <- c(-5, 0, 2)
    plot(r)
    plot(r,
      col = pal(length(cuts)), 
      # Add one more cut on the legend
      breaks = c(cuts, 3), 
      legend.only = TRUE, horizontal = F,
      add = T,
      smallplot = c(0.2, 0.22, 0.1, 0.7),
      axis.args = list(at = c(-5, 0, 2)), labels = c(-5, 0, 2)
    )
    
    

    enter image description here