Only update some traces in graph

Not exactly what I wanted but it helped, I ended up using State as I found here https://community.plotly.com/t/extend-or-append-data-instead-of-update/8898
Here is a working code example

import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go


if __name__ == '__main__':
    app = dash.Dash()
    app.layout = html.Div([dcc.Graph(id='graph'),
                           dcc.Input(id='in', value=7, type='number')])

    @app.callback(
        Output('graph', 'figure'),
        Input('in', 'value'),
        State('graph', 'figure'))
    def update_figure(v, state):
        if state is None:
            fig = go.Figure()
            x = list(range(10))
            y = list(range(5, 25, 2))
            z = [v] * len(x)
            fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='const'))
            fig.add_trace(go.Scatter(x=x, y=z, mode='lines', name='var'))
            return fig
        offset = [elem['name'] for elem in state['data']].index('var')
        x = state['data'][offset]['x']
        state['data'][offset]['y'] = [v] * len(x)
        return state

    app.run_server()

I think this is a common need so I hope it helps

2 Likes