geom_tile single color as 0, then color scale

20,374

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

Share:
20,374
tjr
Author by

tjr

Updated on July 09, 2022

Comments

  • tjr
    tjr almost 2 years

    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.