I have a question regarding how does Dashboard know which plot to display.
Sample code:
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
# Sample data
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "NYC", "NYC", "NYC"]
})
# Initialize the Dash app
app = Dash(__name__)
# App layout
app.layout = html.Div([
html.H1("Simple Dashboard Example", style={"textAlign": "center"}),
dcc.Dropdown(
id="city-dropdown",
options=[{"label": city, "value": city} for city in df["City"].unique()],
value="SF",
placeholder="Select a city"
),
dcc.Graph(id="bar-chart")
])
# Callback to update the graph based on dropdown selection
@app.callback(
Output("bar-chart", "figure"),
Input("city-dropdown", "value")
)
def update_graph(selected_city):
filtered_df = df[df["City"] != selected_city]
fig = px.bar(filtered_df, x="Fruit", y="Amount", title=f"Fruit Sales in {selected_city}")
return fig
def update_graph2(selected_city):
filtered_df = df[df["City"] != selected_city]
fig = px.bar(filtered_df, x="Fruit", y="Amount", title=f"ANOTHER plot {selected_city}")
return fig
# Run the app
if __name__ == "__main__":
app.run(debug=True)
Questions:
- How does
dcc.Graph(id="bar-chart")know which of theupdate_graphorupdate_graph2to use? Is it just whatever comes immediately after dcc.Graph? - If I want to use
update_graph2, how can I do that without copy+paste?
dcc.Graph(id="bar-chart")knows to useupdate_graphbecause the@app.callbackdecorator links theOutput("bar-chart", "figure")to theupdate_graphfunction. The iddcc.Graph ("bar-chart")matches theOutputcomponent in the callback.update_graph2? if you add a callback decorator, it will have the exact same functionality asupdate_graphexcept that it changes the title of the figure... and it would also lead to a race condition with update_graphdcc.Graphcomponent with uniqueids and then link each to its own callback.