6

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

Tim Herzog
  • 505
  • 1
  • 5
  • 11

2 Answers2

6

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

Tim Herzog
  • 505
  • 1
  • 5
  • 11
-1

Axis labels and scales can be customized in the following formats

px.imshow(df, labels=dict(x='',y=''), x=[], y=[])

code:

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, labels=dict(x='Lowcase Letters', y='Full Name'),
                x=['a','b','c'],
                y=['Joseph','Tomas','Robert'])

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

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • I knew that. I want to leave the axis labels as they were, and change the display values in the hover that appears when you mouse over cells in the heatmap. – Tim Herzog Oct 30 '20 at 04:02
  • Did you run the code? In my environment, the hovered text shows the changed text. – r-beginners Oct 30 '20 at 04:08
  • Yes, I ran your code, and got the result shown in your example, which is not what I want. I want joe, tom, bob on the Y axis and Joseph, Thomas, Robert in the hover box – Tim Herzog Oct 30 '20 at 04:49
  • 1
    This doesn't answer the question. The question is about how to override (or customize) the hoverdata, not how to change figure labels. – Reslan Tinawi Mar 30 '22 at 12:20