Tim Herzog
Tim Herzog

Reputation: 561

Custom hovertemplate for plotly express heatmap

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

Upvotes: 8

Views: 4355

Answers (2)

Tim Herzog
Tim Herzog

Reputation: 561

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

Upvotes: 7

r-beginners
r-beginners

Reputation: 35135

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

Upvotes: -1

Related Questions