Force Plotly相关热图颜色等级为零 - R处的白色

问题描述 投票:2回答:2

我有一个plotly产生的相关热图。比例尺从-1到1.随着相关性越来越强,瓷砖颜色为深红色。随着相关性变得越来越强,瓷砖颜色为深蓝色。我需要将零值设为白色。但是,颜色栏只根据数据集的分布选择零颜色。如何强制零值为白色并位于颜色条的中间?我尝试使用this answer,但无法让它适用于此热图。请帮我疯了!

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

r colors plotly heatmap correlation
2个回答
1
投票

如何使用ggplotggplotly

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的值。 ggplotly然后将ggplot对象转换为plotly对象。


4
投票

使用ggplotly非常简单,但我认为你也可以用plotly来做。你可以试试这个:

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

© www.soinside.com 2019 - 2024. All rights reserved.