How to add specific columns for hover over effect in plotly bar chart

Viewed 764

I am plotting a bar chart and I want to reflect certain columns when hovering over those. How would I add that?

My dataframe

Date       | Sku1 | Sku2 |...|Total_accounts|Total_purchases
2020-01-01 | 12  | 34    | ..| 33           | 55
2020-03-01 | 122 | 343   | ..| 35           | 35
2020-04-01 | 11  | 12    | ..| 13           | 65

However, when plotting the chart, I want to keep the last two columns for hovering purposes (not plotting) and the only SKUS should be displayed in the bars. How do I tweak this?

My plotly code is:

fig=px.bar(df.set_index("Date").pipe(lambda d: d.div(d.sum(axis=1), axis=0)).reset_index(),
   x="Date",
   y=[c for c in df.columns if c != "Date"],).update_xaxes(title='Test', visible=True, showticklabels=True).update_yaxes(title='Test', visible=True, showticklabels=False)
fig.show()
1 Answers

If you only do the necessary columns of data to be graphed, you will get the intended shape. If you specify the original data frame as the hover data, it will be displayed as hover data.

import plotly.express as px

dff = df[['Date','Sku1','Sku2']].set_index("Date").pipe(lambda d: d.div(d.sum(axis=1), axis=0)).reset_index()
fig = px.bar(dff, x="Date",
             y=[c for c in dff.columns if c != "Date"],
             custom_data=[df['Total_accounts'], df['Total_purchases']],
            )
fig.update_xaxes(title='Test', visible=True, showticklabels=True)
fig.update_yaxes(title='Test', visible=True, showticklabels=False)
fig.update_traces(hovertemplate='Date:%{x}<br>value:%{value}<br>Total_accounts:%{customdata[0]}<br>Total_purchases:%{customdata[1]}')

fig.show()

enter image description here

Related