[Python] plotly Dashboard refer to different plot

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    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("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?

    Thanks,J

    Continue reading...

Compartilhe esta Página