简体   繁体   English

Plotly - 如何用 slider 覆盖同一图中的两个图

[英]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.目标:在 Plotly 中使用 slider 时,在同一图中有两个散点图。

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.当前行为: slider 跨过两个散点图,将它们分开并一次显示一个结果。

I attach below a minimal reproducible example adapted from the plotly documentation .下面附上一个根据plotly 文档改编的最小可复制示例。 Instead of simply plotting the sin(x), I also added a second plot with cos(x).除了简单地绘制 sin(x),我还添加了带有 cos(x) 的第二个 plot。 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 .我尝试使用add_traces() ,并创建两个单独的跟踪并使用fig = go.Figure(data=trace_list1+trace_list2)更新它们,如下所示

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 .附上Plotly 社区维护的论坛上给出的答案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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