I'm working on a heatmap where my values range from 0-40 and I'd like to have my 0s be colored white while the other values from 1-40 are colored with a gradient. I've experimented with a few options but none seem to accomplish exactly what I'm hoping to do.
The code below is the closest I've been able to get, where I set the limits for the scale fill gradient to 1-40, but this makes 0s appear gray not white:
ggplot(dataframe, aes(x=xvar, y=yvar, fill=n))
geom_tile(color="white", size = 0.25)
geom_text(aes(label = n))
scale_fill_gradient(low="gold", high="darkorchid", limits=c(1, 40))
Is there a way to somehow combine scale_fill_manual and scale_fill_gradient to achieve this? Or is there a completely different function I can try?
Thanks!
CodePudding user response:
I used Gregor Thomas's suggestion and created a new variable called "n_nas" where I coded my zeros as NA. I used "n_nas" as the fill but used the original "n" variable for the labels so that they still appeared as zeros in the heatmap. Here is my final code:
dataframe$n_nas <- ifelse(dataframe$n==0,NA,dataframe$n)
ggplot(dataframe, aes(x=xvar, y=yvar, fill=n_nas))
geom_tile(color="white", size = 0.25)
geom_text(aes(label = n))
scale_fill_gradient(low="gold", high="darkorchid", na.value="white"))
Thanks!
CodePudding user response:
Perhaps you could make your own palette, e.g.
library(ggplot2)
colors <- colorRampPalette(colors = c("gold", "darkorchid"))
new_pal <- c("white", colors(9))
df <- data.frame(xvar = 1:10,
yvar = 1:10,
n = LETTERS[1:5])
ggplot(df, aes(x=xvar, y=yvar, fill=n))
geom_tile(color="white", size = 0.25)
geom_text(aes(label = n))
scale_fill_manual(values = new_pal)
Created on 2022-06-07 by the reprex package (v2.0.1)