I need help for this problem, I passed all last week on it and I didn't find the solution:
I tried to make a dynamic pie chart with a "Total" title of the pie for each date present in my dataframe.
I have succeed to make a pie chart for each date in the dropdown menu with the "visible" option, but I'm block on the dynamic title with the total which change for each pie visible.
Here a picture of what I want to do:
Pie chart with dropdown menu and dynamic title
Here the dataframe structure:
DL Link of Data in csv (for testing the code):
https://www.transfernow.net/dl/20220801IDAIzPJ5
And here the code:
import plotly.express as px
config = {'displaylogo': False}
most_recent_date = data['date'].max()
date_dernier_mois = [most_recent_date]
default_date = str(date_dernier_mois)[2:-2]
# simplify - use value_counts() on whole dataframe
df_vc = data.value_counts()
# create a figure for each date
figs = {
c: px.pie(df_vc.loc[c].reset_index(), values="Valeur", names="Type_usage",
labels="Type_usage",
title=(f"<b>Total : {df_vc.loc[c].reset_index().Total.unique()} </b>"),
hover_data=['Total']).update_traces(
name=c, visible=False, hovertext = "Unite : kWh", pull = 0.05
)
for c in df_vc.index.get_level_values("date").sort_values(ascending=False).unique()
}
# integrate figures per date into one figure
defaultcat = df_vc.index.get_level_values("date").unique().sort_values(ascending=False)[0]
fig = figs[defaultcat].update_traces(visible=True)
for k in figs.keys():
if k != defaultcat:
fig.add_traces(figs[k].data)
# finally build dropdown menu
fig.update_layout(
updatemenus=[
{
"buttons": [
{
"label": k,
"method": "update",
# list comprehension for which traces are visible
"args": [{"visible": [kk == k for kk in figs.keys()]}],
}
for k in figs.keys()
],
"direction": "down", "x": 0.07, "y": 1.15, "bgcolor":'#1F2F40',
"bordercolor":"#1F2F40"
}
]
)
fig.update_layout(autosize = True)
fig.update_layout(showlegend=False)
fig.update_layout(
title={
'x':0.5,
'xanchor': 'center'
})
fig.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='#CACFD3'))
fig.update_traces(textinfo='label+percent', textfont_size=12)
fig.show(renderer="colab")
Thanks in advance
A title must be added as an argument to the button. The following describes only the configuration part of the button.
#finally build dropdown menu
fig.update_layout(
updatemenus=[
{
"buttons": [
{
"label": k,
"method": "update",
# list comprehension for which traces are visible
"args": [{"visible": [kk == k for kk in figs.keys()]},
{"title": (f"<b>{k} Total : {df_vc.loc[k].reset_index().Total.unique()} </b>")} # update
],
}
for k in figs.keys()
],
"direction": "down", "x": 0.07, "y": 1.15, "bgcolor":'#1F2F40',
"bordercolor":"#1F2F40"
}
]
)