首页 文章

为plotly热图自定义悬停文本

提问于
浏览
3

我有 matrix (来自几个条件的基因表达):

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

我希望在 R 中使用 plotly 绘制为 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"))

但事实并非如此 . 实际上,当我将鼠标悬停在情节上时,我看不到任何文字 .

请注意,我正在使用 matrix 而不是 melted data.frame .

2 回答

  • 3

    您将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)
    
  • 1

    因此,plotly中的 ~ 语法被设计为用作 data = ... 对象的引用,如 data$... . 由于's heat map doesn' t使用了 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
    

    如果你想为文本构建一个多行hoverinfo,只需在 text.mat 中使用内联 <\br> 标签,并在图中将它们作为html读取并在渲染时创建行返回 .

相关问题