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.
There is an option for the scale_*_gradient
family of functions that handles out of bounds values (oob
).
The default (oob = scales::censor
) replaces out of bound values with NA
.
You can change it to oob = scales::squish
which squishes values into range.
Therefore, this should solve your issue:
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), oob = scales::squish)+
theme_bw()
Note that this may return the following warning:
Warning message: Removed 10 rows containing missing values (
geom_raster()
).
This warning can safely be ignored. This is just letting you know that the values < 15 and > 20 have been omitted from the plot.