Geom_tile single color as 0, then color scale

I want to create a heat map where with a color pallet from green to red, but the values ​​0 are in white. I started with a geom_tile heatmap with various fill colors based on factor and others on SO, but can't get what I need. For example, with the following database:

df <- data.frame(expand.grid(1:10,1:10)) df$z <- sample(0:10, nrow(df), replace=T) 

I can create this plot:

 ggplot(df,aes(x = Var1,y = Var2,fill = z)) + geom_tile() + scale_fill_gradient(low = "green", high = "red") 

enter image description here But I want the values ​​equal to zero to be white. So this becomes part of:

 ggplot(df,aes(x = Var1,y = Var2,fill = z)) + geom_tile() + scale_fill_gradient(low="green", high="red", limits=c(1, 10)) 

enter image description here

And this gets 0 as white, but I lose green to red:

 ggplot(df,aes(x = Var1,y = Var2,fill = z)) + geom_tile() + scale_fill_gradient(low = "white", high = "red") 

enter image description here

And I can't use the brewer scales at all (although I think I am missing something simple based on error).

 ggplot(df,aes(x = Var1,y = Var2,fill = z)) + geom_tile() + scale_fill_brewer("Greens") 

Error: continuous value applied to discrete scale

Should I just replace 0 with NA? Any help would be greatly appreciated.

+6
source share
1 answer

You can use scale_fill_gradientn() :

 ggplot(df,aes(x = Var1,y = Var2, fill = z)) + geom_tile() + scale_fill_gradientn(colours = c("white", "green", "red"), values = c(0,0.1,1)) 

enter image description here

+5
source

Source: https://habr.com/ru/post/1014688/


All Articles