The following code presents a way to add two traces to a Plotly figure:
import plotly.graph_objs as go
fig = go.Figure()
fig.add_trace(go.Scatter(
x = [0, 1, 2, 3], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 0",
))
fig.add_trace(go.Scatter(
x = [5,6,7,8], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 1",
))
fig.show()
Which looks like this:

Is it possible to merge these two traces into a single one such that they appear under the same title in the legend and share the same visual properties (i.e, color, markers, etc)? More over, merging these traces should enable toggling the visibility when clicking the title in the legend.
The other answer here is excellent, but I'll post an alternative solution for those interested. If for some reason you don't want to add another column to your dataframe (or maybe you're not using dataframes), you can specify the color of each trace and put your traces in the same legend group to ensure they toggle together.
This is also a bit closer to your original code syntax wise, but it is bit more of a workaround stylistically.
import plotly.graph_objs as go
fig = go.Figure()
trace_color = "#636EFA" ## default plotly blue
fig.add_trace(go.Scatter(
x = [0, 1, 2, 3], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace 0",
marker = dict(color = trace_color),
showlegend = False,
legendgroup = "Trace",
))
fig.add_trace(go.Scatter(
x = [5,6,7,8], y = [1, 2, 3, 4],
mode = 'lines+markers',
name = "Trace",
marker = dict(color = trace_color),
legendgroup = "Trace",
))
fig.show()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With