0

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:

  1. How does dcc.Graph(id="bar-chart") know which of the update_graph or update_graph2 to use? Is it just whatever comes immediately after dcc.Graph?
  2. If I want to use update_graph2, how can I do that without copy+paste?
4
  • The dcc.Graph(id="bar-chart") knows to use update_graph because the @app.callback decorator links the Output("bar-chart", "figure") to the update_graph function. The id dcc.Graph ("bar-chart") matches the Output component in the callback. Commented Aug 30 at 18:56
  • thanks! what if i want to use update_chart2 but still keep update_chart? is the only solution to move the function up? Commented Aug 31 at 23:21
  • can you explain what you want to do with update_graph2 ? if you add a callback decorator, it will have the exact same functionality as update_graph except that it changes the title of the figure... and it would also lead to a race condition with update_graph Commented Sep 1 at 2:49
  • You would probably need to use a separate dcc.Graph component with unique ids and then link each to its own callback. Commented Sep 1 at 14:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.