在Jupyter笔记本中使用Bokeh小部件更新Bokeh图。

5

我希望能够在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
谢谢,问题已经提交 - joergd
1个回答

6

通过在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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接