Force Plotly correlation heatmap colorscale to be white at zero - R
我在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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 ="")) |
使用
1 2 3 4 5 6 7 8 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); |
说明:在