Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize hover text for plotly heatmap

I have a matrix (gene expression from several conditions):

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

Which I want to plot as a heatmap using plotly in R.

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"))

works fine.

However, I'd like to add text that would be seen only when hovered over.

I thought this would work:

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"))

But it doesn't. I actually don't see any text when hovering over the plot.

Note that I'm working with a matrix rather than a melted data.frame.

like image 376
dan Avatar asked Mar 10 '17 20:03

dan


People also ask

What is hover name in plotly?

Hover Labels is the most depectively-power feature for interactive visualization in plotly, for user it is the ability to reveal more information about the data points by moving the cursor (mouse) over the point and having a hover label appear.

Is plotly customizable?

Figures made with Plotly Express can be customized in all the same ways as figures made with graph objects, as well as with PX-specific function arguments. New to Plotly? Plotly is a free and open-source graphing library for Python.

What does Add_trace do in plotly?

Adding Traces New traces can be added to a plot_ly figure using the add_trace() method. This method accepts a plot_ly figure trace and adds it to the figure. This allows you to start with an empty figure, and add traces to it sequentially.


1 Answers

You are passing an array of 50x10 into your heatmap but a list of 50 entries as hoverinfo. Both the input for the heatmap and the text must have the same dimensions.

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)
like image 188
Maximilian Peters Avatar answered Sep 30 '22 13:09

Maximilian Peters