I am working on a Dash project that shows some financial information. I created a “histogram” that is more of a bar chart, that shows my expenses for each month. So each month is a bar, which is divided into different categories, like “groceries”, “transport” etc.
So I already made this plot and everything worked, but now I wanted to incorporate callbacks and it does not work and I am a bit confused tbh. I want to select months, through a dropdown. The data in the plot should be from only these months. I can create the plot and it shows in my dashboard BUT I call the “update_bar_chart” function in my script and there is no callback functionality. If I try it without calling it, there is no plot on my dashboard and I am not sure why. As far as I understand the callback function wraps the next function and should call it automatically. I followed some tutorials and they also dont call their update function.
My code shows the graph like this:
def render(app: Dash, data: pd.DataFrame) -> html.Div:
@app.callback(
Output(ids.BAR_CHART, "children"),
Input(ids.MONTH_DROPDOWN, "value")
)
def update_bar_chart(data: pd.DataFrame) -> html.Div:
filtered_data = data
color_map={
"Wohnen": "#636efa",
"Nahrungsmittel": "#ef553b",
"Telekommunikation": "#ff6692",
"Verkehr": "#00cc96",
"Essen gehen": "#ab63fa",
"Inneneinrichtung": "#ffa15a",
"Gesundheit": "#19d3f3",
"Freizeit": "#b6e880",
}
fig = px.histogram(
filtered_data,
x=filtered_data['monat'],
y=filtered_data['Betrag (€)'],
color=filtered_data["consumption_categories"],
labels={'sum of y':'Money Spent',
'x' : 'Monat'},
text_auto=True,
range_y = [0, -2500],
color_discrete_map=color_map
)
return html.Div(dcc.Graph(figure=fig), id=ids.BAR_CHART)
bar_chart = update_bar_chart(data)
return html.Div(children=[html.H6("Monthly costs"),bar_chart])
I tried it like this and many other things but honestly I am just a bit lost:
def render(app: Dash, data: pd.DataFrame) -> html.Div:
@app.callback(
Output(ids.BAR_CHART, "children"),
Input(ids.MONTH_DROPDOWN, "value")
)
def update_bar_chart(months_selected: list) -> html.Div:
filtered_data = data
color_map={
"Wohnen": "#636efa",
"Nahrungsmittel": "#ef553b",
"Telekommunikation": "#ff6692",
"Verkehr": "#00cc96",
"Essen gehen": "#ab63fa",
"Inneneinrichtung": "#ffa15a",
"Gesundheit": "#19d3f3",
"Freizeit": "#b6e880",
}
fig = px.histogram(
filtered_data,
x=filtered_data['monat'],
y=filtered_data['Betrag (€)'],
color=filtered_data["consumption_categories"],
labels={'sum of y':'Money Spent',
'x' : 'Monat'},
text_auto=True,
range_y = [0, -2500],
color_discrete_map=color_map
)
return html.Div(dcc.Graph(figure=fig), id=ids.BAR_CHART)
return html.Div(id=ids.BAR_CHART)
def render(app: Dash, data: pd.DataFrame) -> html.Div:
all_months = data['monat'].unique()
return html.Div(
children=[
html.H6("Months"),
dcc.Dropdown(
id=ids.MONTH_DROPDOWN,
options=[{"label": month, "value": month} for month in all_months],
value=all_months,
multi=True,
),
],
),