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

时间:2018-05-02 00:03:21

标签: r colors plotly heatmap correlation

我在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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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,确保白色对应的值为0ggplotly然后将ggplot对象转换为plotly对象。

答案 2 :(得分:1)

对于 plotly,使用 graph_objects.Heatmap 对象,因为您知道热图值的限制,您可以只设置 zmaxzmid、{{1} } 参数分别设置为 zmin1, 0, -1 参数设置为中间为白色的任何色阶,例如 colorscale