Extra data in hover over a heatmap

If there were a newbie section I would use it because I suspect I ought to know the answer. Enough grovelling.

I’m using python in a notebook and I have a heatmap, something like 20x50, and there isn’t room to display the underlying data so I want display it in a hover. This code doesn’t work.

import plotly.graph_objects as go
import numpy as np

fig = go.Figure(data=go.Heatmap(
                    z=[[1, 20, 30],
                      [20, 1, 60],
                      [30, 60, 1]],
                    text=[['one', 'twenty', 'thirty'],
                          ['twenty', 'one', 'sixty'],
                          ['thirty', 'sixty', 'one']],

                    texttemplate="--%{text}--",
                    textfont={"size":20}))
data = np.stack([['ONE', 'TWENTY', 'THIRTY'],
                          ['TWENTY', 'ONE', 'SIXTY'],
                          ['THIRTY', 'SIXTY', 'ONE']]),
fig.update_traces( customdata = data )
fig.update_traces( hovertemplate = "<<${customdata[0]}>>" )

fig.show()

It shows the heatmap but the value of the customdata hasn’t been subsituted.

I have found umpteen examples of doing this with a scatter plot but none with a heatmap so I might have to resort to using a scatterplot to do it.

Hi, you know that i’d be glad to try this code and figure out what happen, but don’t have the time now. But, plotly under the hood uses dataframes, why don’t try to wrap your data in a df and fine tune after that? Sorry, if I’m wrong, i’ll try your code later in a couple of hours.

I don’t understand why this works and my previous try didn’t, but I discovered this by serendipity and tinkering with the code at Hover text and formatting in Python

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
np.random.seed(0)
z1 = np.random.random((3, 3))
uppercase = [['ONE', 'TWENTY', 'THIRTY'],
                          ['TWENTY', 'ONE', 'SIXTY'],
                          ['THIRTY', 'SIXTY', 'ONE']]
data = np.dstack(( uppercase,))
fig = make_subplots()
fig.add_trace(go.Heatmap(
    z=[[1, 20, 30],
                  [20, 1, 60],
                  [30, 60, 1]],
                   text=[['one', 'twenty', 'thirty'],
                          ['twenty', 'one', 'sixty'],
                          ['thirty', 'sixty', 'one']],
         texttemplate="--%{text}--",
    customdata=data,
    hovertemplate='<b>%{customdata[0]}</b>',
    coloraxis="coloraxis1", name=''),
    1, 1)

fig.update_layout(title_text='Hover for Extra Data !!')
fig.show()
1 Like

Good job, dude! I’ve saved to further advice!

Although I have a working solution, I would still like an explanation of why my fisrt effort didn’t work and why using subplots was necessary.

@Haydon: In your original code substitute

with:

fig.update_traces( hovertemplate = "<<%{customdata}>>" )

1 Like