I'm trying to modify the scale of a heatmap with geom_raster such that the color change occurs over a subset of the data and anything outside that subset doesn't get any more or less colorful.
library(tidyverse)
library(viridis)
library(reshape2)
q <- letters[1:5]
w <- rev(letters)[1:5]
x1 <- rnorm(5, 0, 1)
x2 <- rnorm(5, 0, 1)
x3 <- rnorm(5, 0, 1)
x4 <- rnorm(5, 0, 1)
x5 <- rnorm(5, 10, 1)
test.df <- melt(data.frame(q,w,x1,x2,x3,x4,x5))
ggplot(test.df, aes(q,variable,fill=value))+geom_raster()+scale_fill_viridis()
If you run that, you get this heatmap:
.
The top row is "hogging" some of the color range. Since the vast majority of the data is between -2 and 2, I'd like to make it so that the color scale change occurs over that range, and anything outside of it is just yellow or purple. To me, anything over 2 should just be "very high" and anything under -2 should be "very low", but the numbers between -2 and 2 are what I want to see.
I don't think cut is what I want because then I need to supply a bunch of colors, and I don't want to remove any data or change any data over some value to some maximum or anything like that. Setting limits in the scale_viridis command helps but removes data outside the limits.


You can use
scale_fill_gradientnto have full control on your color gradient. The code below will assign different colors across[-2, 2]but will keep the edge colors consistent beyond these values. Please try to set seed in your questions usingset.seedfor reproducibility.Simply increase the number of colors and values to extend your color gradient.