如何在ggplot2中自定义中间值和最大值的颜色?

时间:2018-05-01 11:19:24

标签: r ggplot2

我按了this链接,尝试

  • 将0设为白色
  • 值大于2的相同颜色

以下代码

library(reshape2)
library(ggplot2)
library(scales)
ran <- matrix(nrow = 3, ncol = 2, c(-2,-1,0,1,2,3))
ran_melt <- melt(ran)
ggplot(ran_melt, aes(Var1, Var2)) +
  geom_tile(aes(fill = value), color = "white") +
  scale_fill_gradientn(colours = c("red", "white", "blue"),
                       values = rescale(c(min(ran_melt$value), 0, max(ran_melt$value)))) +
  labs(fill = 'legend')

将绘制此

enter image description here

如果我将max(ran_melt$value)更改为2

ggplot(ran_melt, aes(Var1, Var2)) +
  geom_tile(aes(fill = value), color = "white") +
  scale_fill_gradientn(colours = c("red", "white", "blue"),
                       values = rescale(c(min(ran_melt$value), 0, 2))) +
  labs(fill = 'legend')

我得到了这个: enter image description here

那么我怎样才能实现我的两个目标呢?

1 个答案:

答案 0 :(得分:2)

您可以在limits中使用参数oobscale_fill_gradientn来实现您的目标:

ggplot(ran_melt, aes(Var1, Var2)) +
    geom_tile(aes(fill = value), color = "white") +
    scale_fill_gradientn(
        colours = c("red", "white", "blue"),
        limits = c(-2, 2),
        oob = squish) +
  labs(fill = 'legend')

enter image description here

说明:oob = squishlimits 以外的值提供与limits的最小值/最大值相同的颜色/填充值。参见例如有关?scale_fill_gradientn的详细信息,请oob

更新

如果您有非对称limits,则可以将参数valuesrescale一起使用:

ggplot(ran_melt, aes(Var1, Var2)) +
    geom_tile(aes(fill = value), color = "white") +
    scale_fill_gradientn(
        colours = c("red", "white", "blue"),
        limits = c(-1, 2),
        values = rescale(c(-1, 0, 2)),
        oob = squish) +
    labs(fill = 'legend')

enter image description here