我想在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)
这个想法是滑块的JS回调调用python函数 update_plot()
,它改变散景图的数据,然后触发 push_notebook()
.
但是,当我移动滑块时,绘图不会更新,而是some weird glyphs appear in the upper left corner (see red arrow) .
执行 print(plt.data_source.data['y'])
向我显示回调和 update_plot()
实际上是在滑块移动时调用的 . 为什么情节没有正确更新?或者我在这里遗漏了什么?
(我知道我可以使用 ipywidgets.interact
做同样的事情,但我想坚持使用散景小部件 . )
1 回答
通过在
bokeh.layouts.row
布局中显示图形和滑块小部件,我得到了按预期更新的图: