为热图上的连续发散色标设置中点

Don*_*Don 2 r heatmap ggplot2

我需要通过 ggplot2 调整热图的中点位置。我用谷歌搜索了一下,发现scale_fill_gradient2很合身,但颜色似乎与我要找的不匹配。我知道 z 需要从 0 到 1 的范围。下面的示例数据集生成:

library(ggplot2)
library(tibble)
library(RColorBrewer)

set.seed(5)
df <- as_tibble(expand.grid(x = -5:5, y = 0:5, z = NA))
df$z <- runif(length(df$z), min = 0, max = 1)
Run Code Online (Sandbox Code Playgroud)

我尝试用 绘图,scale_fill_gradient2但蓝色并没有像我想要的那样“暗”。

ggplot(df, aes(x = x, y = y)) + 
  geom_tile(aes(fill = z)) + 
  scale_fill_gradient2(
    low = 'red', mid = 'white', high = 'blue',
    midpoint = 0.7, guide = 'colourbar', aesthetics = 'fill'
  ) + 
  scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) + 
  scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Run Code Online (Sandbox Code Playgroud)

版本 1

因此,我正在使用scale_fill_distiller调色板“RdBu”,它带有我需要的色标,但范围和中点不正确。

ggplot(df, aes(x = x, y = y)) + 
  geom_tile(aes(fill = z)) +
  scale_fill_distiller(palette = 'RdBu') + 
  scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) +
  scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Run Code Online (Sandbox Code Playgroud)

版本 2

有没有办法获得第二个色标,但可以选择将中点范围设置为第一个?

Cla*_*lke 8

colorspace 包提供的色阶通常可以让您进行更细粒度的控制。首先,您可以使用相同的色阶但设置中点。

library(ggplot2)
library(tibble)
library(colorspace)

set.seed(5)
df <- as_tibble(expand.grid(x = -5:5, y = 0:5, z = NA))
df$z <- runif(length(df$z), min = 0, max = 1)

ggplot(df, aes(x = x, y = y)) + 
  geom_tile(aes(fill = z)) + 
  scale_fill_continuous_divergingx(palette = 'RdBu', mid = 0.7) + 
  scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) + 
  scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Run Code Online (Sandbox Code Playgroud)

但是,如您所见,这会产生与以前相同的问题,因为您必须离中点更远才能获得更深的蓝色。幸运的是,divergingx 色标允许您独立操作任一分支,因此我们可以创建一个更快地变为深蓝色的色标。您可以使用l3, p3, 和p4直到得到您想要的结果。

ggplot(df, aes(x = x, y = y)) + 
  geom_tile(aes(fill = z)) + 
  scale_fill_continuous_divergingx(palette = 'RdBu', mid = 0.7, l3 = 0, p3 = .8, p4 = .6) + 
  scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) + 
  scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.3.0)于 2019 年 11 月 5 日创建


teu*_*and 8

克劳斯的回答很棒(我是他作品的粉丝),但我想补充一点,如果您使用以下函数,您也可以在普通 ggplot 中保留控制权scale_fill_gradientn()

library(ggplot2)
library(tibble)

set.seed(5)
df <- as_tibble(expand.grid(x = -5:5, y = 0:5, z = NA))
df$z <- runif(length(df$z), min = 0, max = 1)

ggplot(df, aes(x = x, y = y)) + 
  geom_tile(aes(fill = z)) + 
  scale_fill_gradientn(
    colours = c("red", "white", "blue"),
    values = c(0, 0.7, 1)
  ) + 
  scale_x_continuous(expand = c(0, 0), breaks = unique(df$x)) + 
  scale_y_continuous(expand = c(0, 0), breaks = unique(df$y))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

一个显着的缺点是您必须values在重新缩放的空间中提供参数,因此在 0-1 之间。考虑一下,如果您的填充值范围为 0-10,并且希望中点为 0.7,则必须提供values = c(0, 0.07, 1).