1

I have 2 dfs; the first one has values to make a heatmap and the 2nd df has metadata that I want to use on hover.

I've tried many things and this is almost working except there's some behavior I don't understand:

import plotly.express as px
import pandas as pd
import difflib

df1 = pd.DataFrame([[22,33],[23,31]], columns=['A','B'])
df2 = pd.DataFrame([['top_left','top_right'],['bottom_left','bottom_right']], columns=['A','B'])
print(df1)
print(df2)

fig = px.imshow(df1, 
                color_continuous_scale=px.colors.diverging.RdYlGn, 
                title='QC')

def ff(sample, pos, tmp):
    
    d=tmp.to_dict()
    s2 = list(d.keys())[0]
    
    print(sample, pos, s2, s2 == sample, s2 == 'A', sample == 'A', type(sample), type(s2), list(difflib.ndiff([sample], [s2])))
    
    return sample, pos #1, tmp.loc[pos, sample]

fig.update_traces(hovertemplate="Sample: %{x} <br> Position: %{y} <br> Score: %{z}" +\
                  f" <br> Depths: {ff('%{x}', '%{y}', df2)}")

fig.show()

gives

    A   B
0  22  33
1  23  31
             A             B
0     top_left     top_right
1  bottom_left  bottom_right

%{x} %{y} A False True False <class 'str'> <class 'str'> ['- %{x}', '+ A']

So s2 != sample because it's still %{x} (not 'A'). Which would explain why this didn't work #1, tmp.loc[pos, sample]. I have no idea how to get around this. Any help appreciated!

Just to be clear - what I'm trying to get is 'top_left' if I hover over the top left (A0) of the heatmap.

Liam McIntyre
  • 334
  • 1
  • 13
  • It seems the template string gets built first, i.e. `ff(…)` called, `f`-string interpolations resolved, etc, and then only is the string used as a template (with the `%{x}` and `%{y}` replaced). – Cimbali Aug 17 '21 at 07:22
  • Yep. Any idea how to make this work? – Liam McIntyre Aug 17 '21 at 07:28
  • I can’t test anything because I don’t have plotly here, but you could have a look at passing extra dataframe columns as `custom_data`, see e.g. https://stackoverflow.com/questions/59057881/python-plotly-how-to-customize-hover-template-on-with-what-information-to-show#63185950 – Cimbali Aug 17 '21 at 07:30
  • Hmm, I did read that today but it makes more sense now that I'm deeper into it. Ty – Liam McIntyre Aug 17 '21 at 07:32
  • This also has an example with customdata and a heatmap: https://chart-studio.plotly.com/~empet/15366/customdata-for-a-few-plotly-chart-types/#/ – Cimbali Aug 17 '21 at 07:34

1 Answers1

1

Thanks to Cimbali for finding chart-studio:

import plotly.graph_objects as go
import pandas as pd

df1 = pd.DataFrame([[22,33],[23,31]], columns=['A','B'])
df2 = pd.DataFrame([['top_left','top_right'],['bottom_left','bottom_right']], columns=['A','B'])
fig3 = go.Figure(go.Heatmap(z = df1, customdata= df2, hovertemplate= 'z: %{z}<br> %{customdata}'))
fig3.show()
Liam McIntyre
  • 334
  • 1
  • 13