Search code examples
rggplot2legendcolorbarlegend-properties

How to adjust scale of ggplot legend when saturating color


When creating raster plots, I want to saturate the color bar at min and max levels to emphasize a certain range. In this case, I want to emphasize the mid range (19-30), even though the actual range is 6-56.

x<-c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4)
y<-c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4)
z<-c(20,21,22,23,40,23,6,23,25,24,56,23,20,23,25,20)

DF<-data.frame(x,y,z)


ggplot(DF,aes(x=x, y=y)) +
  geom_raster(aes(fill = z)) +
  scale_fill_gradientn(limits = c(19, 30), 
                       colors = c('blue', "red"), oob = scales::squish)

This is the plot I want, but I'd like the numbers in the legend to represent the true scale of the range within the "z" value. Ideally, the results would be the same plot, but the numbers in the text of the legend would scale from 6-56 (the min and max of "z"). The color gradient in the legend should saturate above 30, and below 19. Indicating to the viewer that all values above 30 are the same color, and all values below 19 are the same color. So while the legend would have ticks for 30-56, but the legend color bar would not change above 30.


Solution

  • You may try this:

    ggplot(DF,aes(x=x, y=y)) +
        geom_raster(aes(fill = z)) +
        scale_fill_gradientn(values = scales::rescale(x=c(min(DF$z),19,30, max(DF$z)), to = c(0,1), from = c(min(DF$z), max(DF$z))),  colors = c('blue','blue', "red", "red"))
    

    enter image description here