Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom hovertemplate for plotly express heatmap

Tags:

python

plotly

I'm trying to use plotly.express in python to generate a heatmap from a pandas dataframe with a custom hover template that includes additional variables. So for example:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'A': [10, 11, 12], 'B': [10, 12, 14], 'C': [12, 14, 16]}, 
       index=['joe', 'tom', 'bob'])

fig = px.imshow(df)
fig.update_layout(xaxis={'title': 'Letters'}, yaxis={'title': 'Nicknames'})
fig.show()

Gives me this:

plotly heatmap

What I want is to add or replace a variable in the hover information, for instance, replace the nicknames with Joseph, Thomas and Robert.

This has to be possible, but I can't figure out how to do it with a heatmap. Is there a straight forward way to do this in plotly.express? Should I use the "go" interface instead (if so, how)?

like image 887
Tim Herzog Avatar asked Jun 28 '26 12:06

Tim Herzog


1 Answers

I think I found the answer:

import pandas as pd
import numpy as np
import plotly.express as px

df = pd.DataFrame({'A': [10, 11, 12], 'B': [10, 12, 14], 'C': [12, 14, 16]}, 
       index=['joe', 'tom', 'bob'])

names = ['Joseph', 'Thomas', 'Robert']
fig = px.imshow(df)
fig.update(data=[{'customdata': np.repeat(names, len(df.columns)).reshape(3, 3),
    'hovertemplate': 'Letter: %{x}<br>Nickname: %{y}<br>Fullname: %{customdata}<br>Color: %{z}<extra></extra>'}])
fig.update_layout(xaxis={'title': 'Letters'}, yaxis={'title': 'Nicknames'})
fig.show()

enter image description here

like image 174
Tim Herzog Avatar answered Jun 30 '26 02:06

Tim Herzog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!