geom_tile single color as 0, then color scale

泪湿孤枕 提交于 2020-01-01 02:49:29

问题


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")

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))

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")

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.


回答1:


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))



来源:https://stackoverflow.com/questions/42030624/geom-tile-single-color-as-0-then-color-scale

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!