R ggplot 热图手动分箱并选择中间分箱颜色

R ggplot heatmap manual binning and selecting middle bin color

我正在尝试生成具有不同颜色(红色、白色、蓝色)但白色处于选定值(或移动比例)的热图,而不是数据的自动 fitting/centering .

示例数据集:

set.seed(5)
demo <- data.frame(x = seq(from = -40, to = 40, by = 5), y = 0:5, data = runif(102, min = 0, max = 1))

我生成热图的尝试基于:

library(ggplot2)
library(ggsci)
ggplot(demo) + geom_tile(aes(x = x, y = y, fill = data), color = NA) + scale_fill_gsea()

但是,我想将中心 "white" 部分移动到不同的值,例如 0.9,并且我想设置我自己的离散容器。

通过阅读更多文章和 Whosebug 帖子,我的理解是在使用 scale_fill_manual 之前我必须使用 cut 生成我自己的部分,以便设置我自己的色标.

有没有我缺少的更简单的方法?

谢谢。

使用 scale_fill_gradient2 您可以为中点定义一个自定义值:

ggplot(demo) + 
  geom_tile(aes(x = x, y = y, fill = data), color = NA) + 
  scale_fill_gradient2(low = "blue", mid = "white", high = "red", 
                       midpoint = 0.9, 
                       breaks = seq(0, 1, 0.1), 
                       limits = c(0, 1))