【问题标题】:Customize hover text for plotly heatmap为绘图热图自定义悬停文本
【发布时间】:2017-08-01 07:08:27
【问题描述】:

我有一个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

【问题讨论】:

    标签: r hover heatmap plotly


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      因此,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 中使用内联&lt;\br&gt; 标签,plotly 会将它们读取为 html 并在渲染时创建行返回。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-24
        • 2023-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-28
        • 2012-08-10
        相关资源
        最近更新 更多