Black Lives Matter. Please consider donating to Black Girls Code today.

How to update figure data?

I’d like to change the data of a figure in a sequence of functions. Means I have fig = function0(data) which generates the initial figure object from initial data. The initial figure object is then passed to another updated_fig = update_figure(fig).

I can get the current data traces of a figure with data = fig['data'] (with data=[trace0, trace1]). To append a new trace I could use updated_data = data + (trace2, ). All traces are Scattergl(). If I try to update the figure data with fig['data'] = updated_data I get ValueError: The data property of a figure may only be assigned a list or tuple that contains a permutation of a subset of itself.. What Am I doing wrong?

@fkromer Use fig.add_trace(newtrace)

import numpy as np
import plotly.graph_objects as go

trace1 = go.Scattergl(x=[1,2,3],
                   y =[5, -1, 7],
trace2 = go.Scattergl(x= 1+2*np.random.rand(10),
                  y = 5+8*np.random.rand(10),

fig= go.Figure(data=[trace1], layout=dict(width=600))

1 Like

@empet Could not be easier. Thx a lot.

1 Like