1

I would like to plot a heatmap using ggplot, but have the color scale saturate at both a min and max levels. For example, given this dataset:

MyX<-c(rep(1,10),rep(2,10),rep(3,10),rep(4,10),rep(5,10))
MyY<-rep(seq(1,10),5)
MyFill<-runif(50, min = 10, max = 25)  

MyDF<-data.frame(MyX,MyY,MyFill)

I would like to plot heatmap that highlights values between 15 and 20. So that values below 15 all have the same color (minimum of the color scale) and values above 20 all have the same color (max of the color scale).

I can do this:

ggplot(data = MyDF, aes(x=MyX, y=MyY)) +
  geom_raster(aes(fill = MyFill), interpolate=TRUE)+
  scale_y_reverse(lim=c(10,1))+
  scale_fill_gradient2(limits=range(15,20))+
  theme_bw()

But this grays out the colors below 15 and above 20. I'd like to something similar, but as opposed to graying out the colors, just saturating them at min and max values.

Vint
  • 413
  • 6
  • 17

1 Answers1

1

You could use scale_fill_gradientn instead. And just set the colors for the limits to be the same as the colors for the range you want to highlight.

ggplot(data = MyDF, aes(x=MyX, y=MyY)) +
  geom_raster(aes(fill = MyFill), interpolate=TRUE)+
  scale_y_reverse(lim=c(10,1))+
  scale_fill_gradientn(breaks=c(-Inf, 15,20, Inf), colors=c("red","red","blue","blue"))+
  theme_bw()
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • The above is not working as I expected. If I wanted to change the focus range (change c(-Inf, 15,20, Inf) to c(-Inf, 19,20, Inf), the plot does not change at all. Looking at this statement from https://stackoverflow.com/questions/13888222/ggplot-scale-color-gradient-to-range-outside-of-data-range--- "It's very important to remember that in ggplot, breaks will basically never change the scale itself. It will only change what is displayed in the guide or legend." I'm looking to change the scale itself. Similar to changing the limits arg, but without turning everything outside the limits grey – Vint Nov 27 '20 at 21:10