Search code examples
plotlydata-visualizationvisualizationplotly-dashplotly-python

Accept two inputs on a callback in plotly


I want to update a line chart in real-time on the dashboard. I have dashboard built in dash using plotly.

On the dashboard, I have a line chart. There is a dropdown and that determines what data is displayed and then I also want it to update in real-time, based on whichever dropdown option was selected.

As a result, I want the update_chart function to accept two inputs:

  • The dropdown option that was selected

  • The time interval used to make it update in real time

This is what the code looks like right now

@app.callback(Output('live-update-text', 'children'),
              Input('interval-component', 'n_intervals'))
def update_metrics(n):
    lon, lat, alt = satellite.get_lonlatalt(datetime.datetime.now())
    style = {'padding': '5px', 'fontSize': '16px'}
    return [
        html.Span('Longitude: {0:.2f}'.format(lon), style=style),
        html.Span('Latitude: {0:.2f}'.format(lat), style=style),
        html.Span('Altitude: {0:0.2f}'.format(alt), style=style)
    ]

This is what I want it to look like

@app.callback(Output('live-update-text', 'children'),
              Input('interval-component', 'n_intervals')
                AND Input('dropdown-option', 'value')
def update_metrics(n, value):
    lon, lat, alt = satellite.get_lonlatalt(datetime.datetime.now(), satellite_name = value)
    style = {'padding': '5px', 'fontSize': '16px'}
    return [
        html.Span('Longitude: {0:.2f}'.format(lon), style=style),
        html.Span('Latitude: {0:.2f}'.format(lat), style=style),
        html.Span('Altitude: {0:0.2f}'.format(alt), style=style)
    ]

Notice that I added another input to pull in the dropdown value.


Solution

  • Try likewise -

    @app.callback(Output('live-update-text', 'children'),
                  [Input('interval-component', 'n_intervals'),\
                   Input('dropdown-option', 'value')],
                   prevent_initial_call = True)
    def update_metrics(n, value):
        lon, lat, alt = satellite.get_lonlatalt(datetime.datetime.now(), satellite_name 
        = value)
        style = {'padding': '5px', 'fontSize': '16px'}
        return [
            html.Span('Longitude: {0:.2f}'.format(lon), style=style),
            html.Span('Latitude: {0:.2f}'.format(lat), style=style),
            html.Span('Altitude: {0:0.2f}'.format(alt), style=style)
        ]