简体   繁体   中英

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

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()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM