我希望能够在Jupyter笔记本中使用Bokeh小部件来更新Bokeh图表。我的(有些狡猾的)代码如下:
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()
,该函数更改Bokeh绘图的数据,然后触发push_notebook()
。然而,当我移动滑块时,绘图没有更新,但是一些奇怪的图形出现在左上角(见红色箭头)。
执行
print(plt.data_source.data['y'])
向我显示,回调和update_plot()
实际上在滑块移动时被调用。为什么绘图没有得到正确的更新?或者我漏掉了什么?(我知道可以使用
ipywidgets.interact
来做同样的事情,但我想坚持使用Bokeh小部件。)
push_notebook
)在另一个正在进行的事件处理(滑块回调)期间中途出现了问题。 "奇怪的字形" 实际上是整个图形缩小到最小画布大小(我认为是20x20像素)。我建议您在 GitHub 问题跟踪器 上提交此信息。 - bigreddot