joe*_*rgd 5 widget bokeh jupyter
我想使用 jupyter 笔记本中的散景小部件来更新散景图。我的(有点hacky)代码如下所示:
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
from bokeh.models import CustomJS, Slider
output_notebook()
power = 0.5
x = [1,2,3]
y = [i**power for i in x]
fig = figure()
plt = fig.circle(x, y)
def update_plot(power):
x = plt.data_source.data['x']
plt.data_source.data['y'] = [i**power for i in x]
push_notebook(handle=bokeh_handle)
bokeh_handle = show(fig, notebook_handle=True)
##### new notebook cell #####
callback = CustomJS(code="""
if (IPython.notebook.kernel !== undefined) {
var kernel = IPython.notebook.kernel;
cmd = "update_plot(" + cb_obj.value + ")";
kernel.execute(cmd, {}, {});
}
""")
slider = Slider(start=0.1,
end=1,
value=1,
step=.05,
title="power",
callback=callback)
show(slider)
Run Code Online (Sandbox Code Playgroud)
这个想法是滑块的 JS 回调调用 python 函数update_plot(),该函数更改散景图的数据,然后触发push_notebook().
但是,当我移动滑块时,绘图没有更新,但左上角出现一些奇怪的字形(参见红色箭头)。
执行print(plt.data_source.data['y'])告诉我,回调update_plot()实际上是在滑块移动时调用的。为什么剧情没有正确更新?或者我在这里遗漏了什么?
(我知道我可以使用 做同样的事情ipywidgets.interact,但我想坚持使用散景小部件。)
我通过在布局中显示图形和滑块小部件来按预期更新绘图bokeh.layouts.row:
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
from bokeh.models import CustomJS, Slider
from bokeh.layouts import row
output_notebook()
power = 0.5
x = [1,2,3]
y = [i**power for i in x]
fig = figure()
plt = fig.circle(x, y)
def update_plot(power):
x = plt.data_source.data['x']
plt.data_source.data['y'] = [i**power for i in x]
push_notebook(handle=bokeh_handle)
##### new notebook cell #####
callback = CustomJS(code="""
if (IPython.notebook.kernel !== undefined) {
var kernel = IPython.notebook.kernel;
cmd = "update_plot(" + cb_obj.value + ")";
kernel.execute(cmd, {}, {});
}
""")
slider = Slider(start=0.1,
end=1,
value=1,
step=.05,
title="power",
callback=callback)
bokeh_handle = show(row(fig, slider), notebook_handle=True)
Run Code Online (Sandbox Code Playgroud)