设置中点以在热图上连续发散色标

我需要通过ggplot2调整热图的中点位置。我在Google周围搜索,发现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)

我尝试使用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,breaks = unique(df$y))

设置中点以在热图上连续发散色标

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

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

设置中点以在热图上连续发散色标

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

lesswell 回答:设置中点以在热图上连续发散色标

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,breaks = unique(df$y))

但是,正如您所看到的,这会产生与以前相同的问题,因为您必须离中点较远才能获得更暗的蓝调。幸运的是,发散度色标可以让您独立地控制任一分支,因此我们可以创建一个可以更快地变为深蓝色的色标。您可以和l3p3p4一起玩,直到获得所需的结果。

ggplot(df,mid = 0.7,l3 = 0,p3 = .8,p4 = .6) + 
  scale_x_continuous(expand = c(0,breaks = unique(df$y))

reprex package(v0.3.0)于2019-11-05创建

,

Claus的回答很好(我很喜欢他的作品),但是我想补充一点,如果您使用scale_fill_gradientn()函数,您也可以在vanilla ggplot中保留控制权:>

library(ggplot2)
library(tibble)

set.seed(5)
df <- as_tibble(expand.grid(x = -5:5,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,breaks = unique(df$y))

enter image description here

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

本文链接:https://www.f2er.com/3156777.html

大家都在问