2

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?

Astrodude11
  • 109
  • 2
  • 5
  • 11

2 Answers2

3

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!

Derek O
  • 16,770
  • 4
  • 24
  • 43
  • 1
    I used this [SO issue/answer](https://stackoverflow.com/questions/59057881/python-plotly-how-to-customize-hover-template-on-with-what-information-to-show) as a reference for a solution. I will answer my own question. Thanks for the suggestion. – Astrodude11 Oct 09 '21 at 18:33
  • This is apparently not really a bug. See https://github.com/plotly/plotly.py/issues/3419 – Lucas Jan 03 '22 at 10:45
0

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()
Astrodude11
  • 109
  • 2
  • 5
  • 11
  • Did this work as intended for you? – Derek O Oct 13 '21 at 15:21
  • 2
    No. The hover text is displayed as literal text: "Smokes: %{customdata[0]}". I raised an issue on [GitHub](http://github.com/plotly/plotly.py/issues/3419). See their response. – Astrodude11 Oct 14 '21 at 03:20