简体   繁体   中英

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:

热图

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

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

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM