[英]Force Plotly correlation heatmap colorscale to be white at zero - R
我有一個在plotly
生成的相關熱圖。 比例尺從 -1 到 1。隨着相關性變得越來越強,圖塊的顏色會更深紅色。 隨着相關性變得越來越強,瓷磚的顏色會更深藍色。 我需要將零值設為白色。 但是,colorbar 只是根據數據集的分布選擇零顏色。 如何將零值強制為白色並位於顏色條的中間? 我嘗試使用此答案,但無法使其適用於此熱圖。 請幫助我快瘋了!
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 = ""))
使用ggplotly
非常簡單,但我認為您也可以使用plotly
做到這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 = ""))
如何使用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
對象。
隨着plotly
,使用graph_objects.Heatmap
對象,因為你知道你可以只設置熱圖的值的限制zmax
, zmid
, zmin
參數1, 0, -1
分別與colorscale
參數任何colorscale與白中間,比如RdBu
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.