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

2 Likes

Dear Matteo @ghtmtt

Hi

Interesting topic and Useful!.

I had problem with adding a px.line_3d to the figure and I couldn’t add it using fig.add_trace(go.line_3d) because go doesn’t have line_3d and for some reasons I can’t use go.Scatter3d But your first scenario helped me :+1: