本日は
Dashの対話機能の練習
として $x$ の $a$ 乗を与える関数 $x^a$ の可視化と $a$ をパラメータとして動かした時にどのように変化するかをみてみましょう.
実装例
import dash
import dash_html_components as html
import dash_core_components as dcc
import numpy as np
app = dash.Dash()
graph = dcc.Graph(id='graph-with-slider',
figure={'layout': dict(height=400, width=300)})
slider = dcc.Slider(id='slider', min=0, max=20, value=3, step=0.1)
app.layout = html.Div(children=[graph,
html.Label('power'),
slider],
style=dict(height=400, width=400))
@app.callback(
dash.dependencies.Output(component_id='graph-with-slider',
component_property='figure'),
[dash.dependencies.Input(component_id='slider',
component_property='value')])
def update_figure(power):
xs = np.linspace(0, 1, 100)
ys = pow(xs, power)
data = [dict(x=xs, y=ys, type='line')]
return dict(data=data)
def main():
app.run_server()
if __name__ == '__main__':
main()
実行例
power の下にあるスライダーを動かすとそれに応じてコールバック関数としてデコレートされた update_figure
関数が呼び出されます.この関数は,ここでは,id
がslider
のコンポーネントであるSliderのvalue
を引数として受け取り,id
がgraph-with-slider
であるコンポーネントの figure
キーの値(呼び方はこれでで良いのだろうか?)を更新させるためにオプジェクトを返します.
余談
このグラフを眺めていると$x$の$n$乗を与える関数列
\left\{ x^n \right\}_{n=1}^{\infty}
の一様収束性を連想しますね.
懐かしや.