Plotly – how to overlay two plots in same figure with slider

Question:

Aim: Having two scatter plots in the same figure while using a slider in Plotly.

Expected behavior: Show a figure with two plots updating simultaneously and sharing the same "slider step".

Current behavior: The slider steps over both scatter plots, separating them and showing one result at a time.

I attach below a minimal reproducible example adapted from the plotly documentation. Instead of simply plotting the sin(x), I also added a second plot with cos(x).
I tried using add_traces(), and also creating two separate traces and the updating them with fig = go.Figure(data=trace_list1+trace_list2) as shown here.

Any help would be much appreciated!

import plotly.graph_objects as go
import numpy as np

# Create figure
fig = go.Figure()

# Add traces, one for each slider step
for step in np.arange(0, 5, 0.5):
    fig.add_traces([
        go.Scatter(
            x=np.arange(0, 10, 0.01),
            y=np.sin(step * np.arange(0, 10, 0.01))),
        go.Scatter(
            x=np.arange(0, 10, 0.01),
            y=np.cos(step * np.arange(0, 10, 0.01)))])

# Make 10th trace visible
fig.data[10].visible = True

# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="update",
        args=[{"visible": [False] * len(fig.data)},
              {"title": "Slider switched to step: " + str(i)}],  # layout attribute
    )
    step["args"][0]["visible"][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)

sliders = [dict(
    active=10,
    currentvalue={"prefix": "Frequency: "},
    pad={"t": 50},
    steps=steps
)]
fig.update_layout(
    sliders=sliders
)
fig.show()
Asked By: Simone P

||

Answers:

I enclose the answer given on the forum maintained by the Plotly community.

# Create and add slider
steps = []
for i in range(len(fig.data)):
    if i % 2 == 0:
        step = dict(
            method="update",
            args=[{"visible": [False] * len(fig.data)},
                  {"title": "Slider switched to step: " + str(i/2)}],  # layout attribute
        )
        step["args"][0]["visible"][i] = True  # Toggle i'th trace to "visible"
        step["args"][0]["visible"][i+1] = True
        steps.append(step)
Answered By: Simone P
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.