How to make zeros white in R ggplot heatmap?

Viewed 209

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!

1 Answers

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!

Related