2017-06-05 49 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