关于颜色:将Plotly相关热图色标强制设为零时为白色-R

Force Plotly correlation heatmap colorscale to be white at zero - R

我在plotly中生成了相关热图。 比例尺范围从-1到1。随着相关性的增强,图块会被涂成深红色。 随着相关性变得越来越弱,图块将被着色为深蓝色。 我需要零值才能显示为白色。 但是,色条仅根据数据集的分布选择零色。 如何强制零值在颜色栏的中间为白色? 我尝试使用此答案,但无法使其适用于此热图。 请帮我生气!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
library(plotly)
library(magrittr)

# compute a correlation matrix
correlation <- round(cor(mtcars), 3)
nms <- names(mtcars)


colorlength <- 100

null_value <- (0 - min(correlation)) / (max(correlation) - min(correlation))        
border <- as.integer(null_value * colorlength)
colorscale <- as.list(1:colorlength)

#colorscale below zero
s <- scales::seq_gradient_pal("blue","white","Lab")(seq(0,1,length.out=border))
for (i in 1:border) {
  colorscale[[i]] <- c((i - 1) / colorlength, s[i])
}

#colorscale above zero
s <- scales::seq_gradient_pal("white","red","Lab")(seq(0,1,length.out=colorlength - border))
for (i in 1:(colorlength - border)) {
  colorscale[[i + border]] <- c((i + border) / colorlength, s[i])
}



plot_ly(x = nms, y = nms, z = correlation,
            key = correlation, type ="heatmap", source ="heatplot",color = ~correlation,
            colorscale = colorscale,
            colorbar = list(len=1)) %>%
      layout(xaxis = list(title =""),
             yaxis = list(title =""))

enter image description here


使用ggplotly非常简单,但是我认为您也可以使用plotly来实现。 您可以尝试以下方法:

1
2
3
4
5
6
7
8
col3 <- colorRamp(c("red","white","blue"))

plot_ly(x = nms, y = nms, z = correlation,
        key = correlation, type ="heatmap", source ="heatplot",color = col3,
        colorscale = colorscale,
        colorbar = list(len=1, limits = c(-1, 1))) %>%
    layout(xaxis = list(title =""),
           yaxis = list(title =""))

enter image description here


如何使用ggplotggplotly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
library(tidyverse);
gg <- correlation %>%
    as.data.frame() %>%
    rownames_to_column("x") %>%
    gather(y, val, -x) %>%
    ggplot(aes(x, y, fill = val)) +
    geom_tile() +
    scale_fill_gradientn(
        colours = c("blue","white","red"),
        limits = c(-1, 1))

# Create plotly object
library(plotly);
ggplotly(gg);

enter image description here

说明:在ggplot中,我们可以使用scale_fill_gradientn显式设置limits,确保白色对应于0的值。 然后,ggplotlyggplot对象转换为plotly对象。