I have created a basic stacked bar graph in Python. The text inside each category contains sales for that category. Additionally, I have used annotations to specify the total of each bar.
Output graph:
Now, when I click on any legend items, the annotations stay where they are and the bar size reduces.
Is there any way to update the totals displayed in the annotation and the positioning of the same using a callback ?
import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd
import numpy as np
# Define the range of months
months = pd.date_range(start='2023-01-01', end='2023-12-31', freq='M')
# Define categories
categories = ['Electronics', 'Clothing', 'Books', 'Groceries', 'Furniture']
# Generate random sales amounts
np.random.seed(0) # For reproducibility
sales_amounts = np.random.randint(100, 1000, size=(len(months), len(categories)))
data = []
for i, month in enumerate(months):
for j, category in enumerate(categories):
data.append([month, category, sales_amounts[i][j]])
df = pd.DataFrame(data, columns=['Month', 'Category', 'Sale Amount'])
df_grouped = df.groupby(['Month', 'Category']).sum().reset_index()
totals = df_grouped.groupby('Month')['Sale Amount'].sum().reset_index()
fig = px.bar(df_grouped, x='Month', y='Sale Amount', color='Category',
title='Total Sales by Month and Category',
labels={'Sale Amount': 'Total Sales', 'Month': 'Month'},
text='Sale Amount')
fig.update_layout(plot_bgcolor='white')
fig.update_traces(textposition = 'inside', marker=dict(line=dict(color='black', width=1)))
for i, month_total in totals.iterrows():
fig.add_annotation(x=month_total['Month'], y=month_total['Sale Amount']+300,
text=f'{month_total["Sale Amount"]:.0f}', showarrow=False, textangle = 90)
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1("Sales Dashboard"),
dcc.Graph(figure=fig, id='sales-graph')
])
if __name__ == '__main__':
app.run_server(port=5555)