Best method to add Trace to existing Figure

Hi all,

what is the best plotly way to add one or more Trace(s) to an existing Figure object using the output of plotly express? One scenario could be:

import plotly.express as px
import plotly.graph_objects as go

fig = go.Figure()
trace1= px.line(x=["a","b","c"], y=[1,3,2], title="first trace")
trace2 = px.line(x=["a","b","c"], y=[50,70,90], title="second trace")

fig.add_trace(trace1.data[0])
fig.add_trace(trace2.data[0])

fig.show()

then we can explicit add the type of plot to the figure (notice also the change from title to name)::


import plotly.express as px
import plotly.graph_objects as go

fig = px.line(x=["a","b","c"], y=[1,3,2], title="first trace")

fig.add_scatter(x=["a","b","c"], y=[50,70,90], name="second trace")

fig.show()

and another one mixes plotly express and graph objects:

import plotly.express as px
import plotly.graph_objects as go

fig = px.line(x=["a","b","c"], y=[1,3,2], title="first trace")

fig.add_trace(go.Scatter(x=["a","b","c"], y=[50,70,90], name="second trace"))

fig.show()

I think all the methods are valid by Iā€™m unsure what is the best one

Thanks to all!

Matteo

1 Like