2017-06-05 52 views
0

我可以指定端點爲colorRamp,以便將值始終映射到單一顏色,而不管其他數據的範圍如何?指定colorRamp端點

我試圖在plotly中創建一個互動關聯圖。以下是一些示例數據。

set.seed(1) 
m <- 4 
cm <- matrix(runif(m**2,-1,1), 
      nrow=m, ncol=m, 
      dimnames=list(letters[1:m],letters[1:m])) 
diag(cm) <- 1 

cm 
#   a   b   c   d 
# a 1.0000000 -0.5966361 0.2582281 0.3740457 
# b -0.2557522 1.0000000 -0.8764275 -0.2317926 
# c 0.1457067 0.8893505 1.0000000 0.5396828 
# d 0.8164156 0.3215956 -0.6468865 1.0000000 

基本上,我試圖創建一個這樣的互動版:

library(corrplot) 
corrplot(cm,method='shade') 

Non-interactive version of desired output

這裏的(那種哈克)我創建的交互關係圖。

div_colors <- c('dark red','white','navy blue') 
grid_labels <- matrix(paste0('Cor(', 
           do.call(paste,c(expand.grid(rownames(cm),colnames(cm)), sep=', ')), 
           '): ', 
           t(round(cm,2)) 
          ), 
          ncol=m,byrow=TRUE) 
library(plotly) 
plot_ly(x = colnames(cm), 
     y = rownames(cm), 
     z = cm, 
     colors = colorRamp(div_colors), 
     type='heatmap', 
     hoverinfo='text', 
     text = grid_labels 
     ) %>% layout(yaxis=list(autorange='reversed')) 

enter image description here

我的問題是,不強制colorRamp端點c(-1,1),白顏色不匹配0的相關性,而暗紅色映射到最低觀察,而不是-1。

+1

set [zmin and zmax](https://plot.ly/r/reference/#heatmap- ZMIN)? – rawr

+0

@rawr工作。如果你想寫出來,我會接受它作爲答案。有點瑣碎,但它不在任何例子中(例如[這裏](https://plot.ly/r/heatmaps/#custom-colorscales)) – C8H10N4O2

回答

1

作爲@rawr在註釋所提到的,解決方案是set zmin and zmax,如:

plot_ly(x = colnames(cm), 
     y = rownames(cm), 
     z = cm, 
     zmin=-1,       # <============ 
     zmax=1,       # <============ 
     colors = colorRamp(div_colors), 
     type='heatmap', 
     hoverinfo='text', 
     text = grid_labels 
) %>% layout(yaxis=list(autorange='reversed')) 

其產生所需的結果。 (圖例欄較短,大概是由於更新版本的默認尺寸發生變化)。 enter image description here