更新散景图与jupyter笔记本中的散景小部件

时间:2016-11-10 17:12:24

标签: widget jupyter bokeh

我想在jupyter笔记本中使用散景小部件来更新散景图。我的(有点hacky)代码看起来像这样:

main()

这个想法是滑块的JS回调调用python函数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) ,它改变散景图的数据,然后触发update_plot()

但是,当我移动滑块时,图表不会更新,而是some weird glyphs appear in the upper left corner (see red arrow)

执行push_notebook()向我显示回调和print(plt.data_source.data['y'])实际上是在滑块移动时调用的。为什么情节没有正确更新?或者我在这里遗漏了什么?

(我知道我可以使用update_plot()做同样的事情,但我想坚持使用散景小部件。)

1 个答案:

答案 0 :(得分:4)

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