Plotly 简明教程

Plotly - Adding Buttons Dropdown

Plotly 通过在绘图区域上使用不同的控件(例如按钮、下拉菜单和滑块等)来提供高度的交互性。这些控件与图形布局的 updatemenu 属性结合使用。可以通过指定要调用的方法来 add button 及其行为。

Plotly provides high degree of interactivity by use of different controls on the plotting area – such as buttons, dropdowns and sliders etc. These controls are incorporated with updatemenu attribute of the plot layout. You can add button and its behaviour by specifying the method to be called.

可以与按钮关联的四种方法如下所示 −

There are four possible methods that can be associated with a button as follows −

  1. restyle − modify data or data attributes

  2. relayout − modify layout attributes

  3. update − modify data and layout attributes

  4. animate − start or pause an animation

图形的 modifying the data and data attributes 时,应该使用 restyle 方法。在下面的示例中,通过 restyle 方法将两个按钮添加到布局中,方法为 Updatemenu()

The restyle method should be used when modifying the data and data attributes of the graph. In the following example, two buttons are added by Updatemenu() method to the layout with restyle method.

go.layout.Updatemenu(
type = "buttons",
direction = "left",
buttons = list([
   dict(args = ["type", "box"], label = "Box", method = "restyle"),
   dict(args = ["type", "violin"], label = "Violin", method = "restyle" )]
))

默认情况下, type 属性的值为 buttons 。要显示按钮的下拉列表,将类型更改为 dropdown 。在更新其布局之前,向 Figure 对象添加一个框跟踪。以下是如何根据单击按钮显示 boxplotviolin plot 的完整代码 −

Value of type property is buttons by default. To render a dropdown list of buttons, change type to dropdown. A Box trace added to Figure object before updating its layout as above. The complete code that renders boxplot and violin plot depending on button clicked, is as follows −

import plotly.graph_objs as go
fig = go.Figure()
fig.add_trace(go.Box(y = [1140,1460,489,594,502,508,370,200]))
fig.layout.update(
   updatemenus = [
      go.layout.Updatemenu(
         type = "buttons", direction = "left", buttons=list(
            [
               dict(args = ["type", "box"], label = "Box", method = "restyle"),
               dict(args = ["type", "violin"], label = "Violin", method = "restyle")
            ]
         ),
         pad = {"r": 2, "t": 2},
         showactive = True,
         x = 0.11,
         xanchor = "left",
         y = 1.1,
         yanchor = "top"
      ),
   ]
)
iplot(fig)

下面给出代码的输出 −

The output of the code is given below −

violin button

单击 Violin 按钮以显示相应的 Violin plot

Click on Violin button to display corresponding Violin plot.

dropdown list button

如上所述, Updatemenu() 方法中 type 键的值被赋值为 dropdown 以显示按钮的下拉列表。绘图如下所示 -

As mentioned above, value of type key in Updatemenu() method is assigned dropdown to display dropdown list of buttons. The plot appears as below −

update method

修改图形的数据和布局部分时,应使用 update 方法。以下示例演示如何在同时更新布局属性(例如图表标题)时更新和显示痕迹。两个对应于 sine and cos wave 的散点迹线添加到 Figure object 。可见性 attributeTrue 的痕迹将显示在绘图上,其他痕迹将被隐藏。

The update method should be used when modifying the data and layout sections of the graph. Following example demonstrates how to update and which traces are displayed while simultaneously updating layout attributes, such as, the chart title. Two Scatter traces corresponding to sine and cos wave are added to Figure object. The trace with visible attribute as True will be displayed on the plot and other traces will be hidden.

import numpy as np
import math #needed for definition of pi

xpoints = np.arange(0, math.pi*2, 0.05)
y1 = np.sin(xpoints)
y2 = np.cos(xpoints)
fig = go.Figure()
# Add Traces
fig.add_trace(
   go.Scatter(
      x = xpoints, y = y1, name = 'Sine'
   )
)
fig.add_trace(
   go.Scatter(
      x = xpoints, y = y2, name = 'cos'
   )
)
fig.layout.update(
   updatemenus = [
      go.layout.Updatemenu(
         type = "buttons", direction = "right", active = 0, x = 0.1, y = 1.2,
         buttons = list(
            [
               dict(
                  label = "first", method = "update",
                  args = [{"visible": [True, False]},{"title": "Sine"} ]
               ),
               dict(
                  label = "second", method = "update",
                  args = [{"visible": [False, True]},{"title": Cos"}]
               )
            ]
         )
      )
   ]
)
iplot(fig)

最初,将显示 Sine curve 。如果单击第二个按钮,则会出现 cos trace

Initially, Sine curve will be displayed. If clicked on second button, cos trace appears.

请注意, chart title 也会相应地更新。

Note that chart title also updates accordingly.

sine curve

为了使用 animate 方法,我们需要添加一个或多个 Frames to the Figure 对象。除了数据和布局之外,还可以将框架作为图形对象中的密钥添加。框架密钥指向一系列图形,其中每一个图形将在触发动画时循环遍历。

In order to use animate method, we need to add one or more Frames to the Figure object. Along with data and layout, frames can be added as a key in a figure object. The frames key points to a list of figures, each of which will be cycled through when animation is triggered.

你可以添加播放和暂停按钮,通过在布局中添加 updatemenus array ,为图表引入动画。

You can add, play and pause buttons to introduce animation in chart by adding an updatemenus array to the layout.

"updatemenus": [{
   "type": "buttons", "buttons": [{
      "label": "Your Label", "method": "animate", "args": [frames]
   }]
}]

在以下示例中,首先绘制 scatter curve 轨迹。然后添加 frames ,它是一个 50 Frame objects 列表,每个列表代表曲线上的 red marker 。请注意,按钮的 args 属性被设置为 None,因此所有帧都将被动画化。

In the following example, a scatter curve trace is first plotted. Then add frames which is a list of 50 Frame objects, each representing a red marker on the curve. Note that the args attribute of button is set to None, due to which all frames are animated.

import numpy as np
t = np.linspace(-1, 1, 100)
x = t + t ** 2
y = t - t ** 2
xm = np.min(x) - 1.5
xM = np.max(x) + 1.5
ym = np.min(y) - 1.5
yM = np.max(y) + 1.5
N = 50
s = np.linspace(-1, 1, N)
#s = np.arange(0, math.pi*2, 0.1)
xx = s + s ** 2
yy = s - s ** 2
fig = go.Figure(
   data = [
      go.Scatter(x = x, y = y, mode = "lines", line = dict(width = 2, color = "blue")),
      go.Scatter(x = x, y = y, mode = "lines", line = dict(width = 2, color = "blue"))
   ],
   layout = go.Layout(
      xaxis=dict(range=[xm, xM], autorange=False, zeroline=False),
      yaxis=dict(range=[ym, yM], autorange=False, zeroline=False),
      title_text="Moving marker on curve",
      updatemenus=[
         dict(type="buttons", buttons=[dict(label="Play", method="animate", args=[None])])
      ]
   ),
   frames = [go.Frame(
      data = [
            go.Scatter(
            x = [xx[k]], y = [yy[k]], mode = "markers", marker = dict(
               color = "red", size = 10
            )
         )
      ]
   )
   for k in range(N)]
)
iplot(fig)

代码的输出如下所示 -

The output of the code is stated below −

play button

单击 play 按钮后,红色标记将开始沿着曲线移动。

The red marker will start moving along the curve on clicking play button.