简体   繁体   中英

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

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

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

在此处输入图片说明

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