Plotly スライダーウィジェット#
※記事内に商品プロモーションを含むことがあります。
公開日
Pythonのインタラクティブなグラフを描画できるライブラリPlotlyにて、スライダーウィジェットを追加する方法を解説します。
Plotlyには、高水準のAPIであるPlotly Expressと呼ばれるものもありますが、この記事では細かい調節ができるgraph_objects
を対象としています。
リンク
スライダーの基礎#
Plotlyの棒グラフ go.Bar
を3つ用意し、スライダーで切り替える例を示します。
スライダーを右に動かすと、棒グラフの数値が増えます。
import plotly.graph_objects as go
fig = go.Figure(
data=[
go.Bar(x=["Alice", "Bob"], y=[1, 2], visible=True),
go.Bar(x=["Alice", "Bob"], y=[2, 4], visible=False),
go.Bar(x=["Alice", "Bob"], y=[3, 6], visible=False),
],
)
steps = []
for i in range(len(fig.data)):
step = dict(
method="update",
args=[{"visible": [False] * len(fig.data)}],
label=f"{i}"
)
step["args"][0]["visible"][i] = True # Toggle i'th trace to "visible"
steps.append(step)
sliders = [dict(
active=0,
currentvalue={"prefix": "Year: "},
pad={"t": 30},
steps=steps
)]
fig.update_layout(sliders=sliders)
fig.update_yaxes(range=(0, 8))
fig.show()