0

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.

Vint
  • 413
  • 6
  • 17
  • 1
    If I understand your objectives correctly, you may try `values = scales::rescale(...)` in `scale_fill_gradientn`, as described e.g. here: [Is it possible to define the “mid” range in scale_fill_gradient2()?](https://stackoverflow.com/questions/21758175/is-it-possible-to-define-the-mid-range-in-scale-fill-gradient2/21758729#21758729); [Increase resolution of color scale for values close to zero](https://stackoverflow.com/questions/20581746/increase-resolution-of-color-scale-for-values-close-to-zero/20584038#20584038) – Henrik Jul 26 '21 at 13:19

1 Answers1

1

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

iago
  • 2,990
  • 4
  • 21
  • 27