Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_tile single color as 0, then color scale

Tags:

r

ggplot2

heatmap

I want to produce a heat map where with a color pallet of green to red, but values of 0 are in white. I got started with geom_tile heatmap with different high fill colours based on factor and others on SO but can't quite 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 gets part way there:

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 the 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 brewer scales at all (though I think I'm missing something simple based on the error).

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

Error: Continuous value supplied to discrete scale

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

like image 528
tjr Avatar asked Feb 03 '17 18:02

tjr


1 Answers

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

like image 92
erc Avatar answered Oct 26 '22 15:10

erc