Search code examples
pythonplotlypython-interactive

Plotly interactive visualizations dropdown


I am attempting to create a plotly dash drop-down whose selection is used to filter a dataframe and generate a pie chart from the filtered dataframe. I started with the working code from plotly interactive visualizations documentation and as carefully as possible went through and deleted all the extra. (all I want is one drop-down and one output graph as per similar stack question).

For now I will stick with the first question that has come to mind relating to the logic of the @app.callback section of the code.

@app.callback(
Output('indicator-graphic', 'figure'),
[Input('choose_species', 'value')])

The input tag makes sense, as there is a dropdown above with id and value equal to the arguments of Input:

html.Div([
        dcc.Dropdown(
            id='choose_species',
            options=[{'label': i, 'value': i} for i in available_indicators],
            value='Pacific Water Shrew'
        )

However, while the out put has a related id:

dcc.Graph(id='indicator-graphic')

there is nothing else in the code with the text figure which I would assume would have to come from the output of a function update_graph as it is called in the example code. There is no other mention of figure in my own code (which doesnt work obviously) nor in the example code (which does work to my surprise, given that I can't figure out how).

Question:

Given the above, how do I tie by @app_callback to my update-graph function. Please keep in mind I am quite new to all coding languages involved.


Solution

  • Based on my experience you can do something like below:

    app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
    
    app.layout = html.Div([html.H5('Drop Down',className='text-center'),
                dcc.Dropdown(
                id='choose_species',
                options=[{'label': i, 'value': i} for i in available_indicators],
                    value='Pacific Water Shrew',
                    multi=True,
                    disabled=False,
                    clearable=True,
                    searchable=True),
                dcc.Graph(id='indicator-graphic',figure={},style={'height':300,'width':'auto'})
    ])
    
    @app.callback(Output('indicator-graphic', 'figure'),
                 [Input('choose_species', 'value')])
    
    def build_graph(species): 
        fig = px.line(df,x='',y='',color='')
        return fig
    
    if __name__ == "__main__":
        app.run_server(debug=False
    

    )

    You need to add dcc.Graph and figure={} in your layout, and under @app.callback you have to add a function to return figure after filtering by dropdown.