Home > Back-end >  Python & Plotly: Adding Hover Data to Density Heat Map
Python & Plotly: Adding Hover Data to Density Heat Map

Time:10-10

As a trivial example, I'm using the first heat map shown on the Plotly 2D Histograms webpage. The documentation references the hover_data parameter but I'm unable to display additional data. The data frame in the example include these columns:

>>> df.columns
Index(['total_bill', 'tip', 'sex', 'smoker', 'day', 'time', 'size'], dtype='object')

According to the said documentation, hover data, such as "size" can be added like this:

>>> fig = px.density_heatmap(df, x="total_bill", y="tip", hover_data=['size'])
>>> fig.show()

However, the generated plot only shows "total_bill", "tip", and "count" in the hover data. What am I missing?

CodePudding user response:

This is definitely a bug with px.density_heatmap. After running fig = px.density_heatmap(df, x="total_bill", y="tip", hover_data=['size']), the hovertemplate should include the size column, but hovertemplate string doesn't include the correct information.

fig.data[0].hovertemplate
'total_bill=%{x}<br>tip=%{y}<br>count=%{z}<extra></extra>'

For the sake of comparison, if we run: fig = px.scatter(df, x="total_bill", y="tip", hover_data=['size']), we can see that the hovertemplate does include the size column embedded in the customdata:

fig.data[0].hovertemplate
'total_bill=%{x}<br>tip=%{y}<br>size=%{customdata[0]}<extra></extra>'

You probably need to use Plotly graph_objects for the time being to display additional df columns in your heatmap when you hover. I can circle back on this answer to show you if you would like!

CodePudding user response:

Thanks to Derek's suggestion and this SO Q&A, I used hover_template, graph_objects, and customdata to plot the data but the custom hover data for the "Smokes" field is not displayed.

import plotly.graph_objects as go
import plotly.express as px


df = px.data.tips()

fig = go.Figure(
    data=go.Histogram2d(
        x=df['total_bill'], 
        y=df['tip'],
        z=df['size'],
        histfunc='sum',
        customdata=[df['smoker']]
    )
)

fig.update_traces(
    hovertemplate='<br>'.join([
        'Bill $: %{x}',
        'Tip $: %{y}',
        'Size: %{z}',
        'Smokes: %{customdata[0]}'
    ])
)

fig.show()
  • Related