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.
If the values only exceed the scale at one end (looks to be the case with your data, you have values greater than 2, but not less than -2) you can change values that exceed your maximum to
NA
in your dataframe and then use thena.value =
option inscale_fill_viridis()
to make all of the NA values a certain color.This solution is less flexible than the other answers, as it won't work if you have values that exceed your range on the high and low end of the scale, but it's an easy, concise way to do this if you only have outliers on one end of the scale.