我在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 = ""))
答案 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 = ""))
答案 1 :(得分:1)
如何使用ggplot
和ggplotly
:
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);
说明:在ggplot
中,我们可以使用scale_fill_gradientn
明确设置limits
,确保白色对应的值为0
。 ggplotly
然后将ggplot
对象转换为plotly
对象。
答案 2 :(得分:1)
对于 plotly
,使用 graph_objects.Heatmap
对象,因为您知道热图值的限制,您可以只设置 zmax
、zmid
、{{1} } 参数分别设置为 zmin
,1, 0, -1
参数设置为中间为白色的任何色阶,例如 colorscale
。