Plotly 简明教程

Plotly - Slider Control

Plotly 有一个方便的 Slider ,可用于通过滑动位于渲染绘图底部的控件上的旋钮,更改绘图的 data/style 视图。

Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot.

Slider control 由不同的属性组成,如下所示 −

Slider control is made up of different properties which are as follows −

  1. steps property is required for defining sliding positions of knob over the control.

  2. method property is having possible values as restyle | relayout | animate | update | skip, default is restyle.

  3. args property sets the arguments values to be passed to the Plotly method set in method on slide.

我们现在在散点图上部署一个简单的滑块控件,该控件将使 sine wave 的频率随着旋钮沿着控件滑动而变化。滑块配置为有 50 个步骤。首先添加 50 条具有递增频率的正弦波曲线,除第 10 条迹线外,其余所有迹线都设置为可见。

We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible.

然后,我们使用 restyle 方法配置每个步骤。对于每一步,所有其他步骤对象都将可见性设置为 false 。最后,通过初始化 sliders 属性来更新 Figure 对象的布局。

Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure object’s layout by initializing sliders property.

# Add traces, one for each slider step
for step in np.arange(0, 5, 0.1):
fig.add_trace(
   go.Scatter(
      visible = False,
      line = dict(color = "blue", width = 2),
      name = "𝜈 = " + str(step),
      x = np.arange(0, 10, 0.01),
      y = np.sin(step * np.arange(0, 10, 0.01))
   )
)
fig.data[10].visible=True

# Create and add slider
steps = []
for i in range(len(fig.data)):
step = dict(
   method = "restyle",
   args = ["visible", [False] * len(fig.data)],
)
step["args"][1][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(active = 10, steps = steps)]
fig.layout.update(sliders=sliders)
iplot(fig)

首先, 10th sine wave 迹线将可见。尝试沿底部水平控件滑动旋钮。你将看到频率发生变化,如下所示。

To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below.

sine wave trace