定制Plotly热力图的悬停文本

5

我有一个矩阵(来自若干情况下的基因表达):

set.seed(1)
mat <- matrix(rnorm(50*10),nrow=50,ncol=10,dimnames=list(paste("C",1:50,sep="."),paste("G",1:10,sep=".")))

我希望使用plotlyR中绘制一个heatmap

require(plotly)
heatmap.plotly <- plot_ly(x=colnames(mat),y=rownames(mat),z=mat,type="heatmap",colors=colorRamp(c("darkblue","white","darkred")),colorbar=list(title="Score",len=0.4)) %>%
  layout(yaxis=list(title="Condition"),xaxis=list(title="Gene"))

很好用。

但是,我想添加只在悬停时可见的文本。

我以为这样会起作用:

conditions.text <- paste(paste("C",1:50,sep="."),rep(paste(LETTERS[sample(26,10,replace=T)],collapse=""),50),sep=":")
heatmap.plotly <- plot_ly(x=colnames(mat),y=rownames(mat),z=mat,type="heatmap",colors=colorRamp(c("darkblue","white","darkred")),colorbar=list(title="Score",len=0.4),hoverinfo='text',text=~conditions.text) %>%
  layout(yaxis=list(title="Condition"),xaxis=list(title="Gene"))

但是它并没有显示任何文本。当悬停在图表上时,我实际上看不到任何文本。

请注意,我正在使用一个矩阵而不是一个融合的数据框。

2个回答

5

您将一个50x10的数组传递到热力图中,但将50个条目的列表作为hoverinfo。热力图和文本的输入必须具有相同的维度。

library(plotly)
set.seed(1)
mat <- matrix(rnorm(50*10),nrow=50,ncol=10,dimnames=list(paste("C",1:50,sep="."),paste("G",1:10,sep=".")))

conditions.text <- paste(paste("C",1:50,sep="."),rep(paste(LETTERS[sample(26,10,replace=T)],collapse=""),500),sep=":")
conditions.text <- matrix(unlist(conditions.text), ncol = 10, byrow = TRUE)

plot_ly(z=mat,
        type="heatmap",
        hoverinfo='text',
        text=conditions.text)

3
所以在plotly中的~语法旨在作为对data = ...对象的引用,例如data$...。由于plotly的热力图不适用于data参数,因此它在这里无法工作。您需要构造一个与mat相同尺寸的矩阵来提供给text = ...参数。这有点笨拙,但可以生成漂亮的图形:
# make a matrix same dimensions as mat
text.mat <- matrix(conditions.text, nrow(mat), ncol(mat))
heatmap.plotly <- plot_ly(x=colnames(mat),y=rownames(mat),z=mat,
                          type="heatmap",colors=colorRamp(c("darkblue","white","darkred")),
                          colorbar=list(title="Score",len=0.4), hoverinfo='text', text=text.mat) %>%
    layout(yaxis=list(title="Condition"),xaxis=list(title="Gene"))
heatmap.plotly

如果你想构建一个多行的悬停信息文本,只需在text.mat中使用内联<\br>标签,plotly将会将其读取为html,并在渲染时创建换行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接