gpt4 book ai didi

r - 强制 Plotly 相关热图色标在零处为白色 - R

转载 作者:行者123 更新时间:2023-12-02 19:28:12 25 4
gpt4 key购买 nike

我有一个用 plotly 生成的相关热图。刻度范围从 -1 到 1。随着相关性变得更强,图 block 的颜色会变深红色。随着负相关性变得更强,图 block 的颜色会变深蓝色。我需要将零值设置为白色。然而,颜色条只是根据数据集的分布选择零的颜色。如何强制零值变为白色并位于颜色条的中间?我尝试使用 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

最佳答案

使用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

关于r - 强制 Plotly 相关热图色标在零处为白色 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com