geom_tile单色为0,然后色阶

geom_tile single color as 0, then color scale

我想生成一个热图,其中的颜色托盘为绿色到红色,但 0 的值是白色的。我从 geom_tile heatmap with different high fill colours based on factor 和其他人开始,但不能完全得到我需要的东西。例如,使用以下数据库:

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

我可以创建这个情节:

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

但我希望等于零的值是白色的。所以这部分到那里:

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

这得到 0 为白色,但我将绿色变为红色:

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

而且我根本无法使用啤酒秤(尽管我认为基于错误我遗漏了一些简单的东西)。

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

错误:提供给离散量表的连续值

我应该用 NA 替换 0 吗?任何帮助,将不胜感激。

您可以使用 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))