How can I get data from a ColumnDataSource object which is synchronized with local variables of Bokeh's CustomJS function?

不想你离开。 提交于 2019-12-03 08:26:56

You can use the ToolEvents for this purpose. See example below.

from bokeh.plotting import figure
from bokeh.client import push_session
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, CustomJS, BoxSelectTool, Range1d, Rect

source = ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))

callback = CustomJS(args=dict(source=source), code="""

        var data = source.get('data');
        var geometry = cb_data['geometry'];


        var width = geometry['x1'] - geometry['x0'];
        var height = geometry['y1'] - geometry['y0'];
        var x = geometry['x0'] + width/2;
        var y = geometry['y0'] + height/2;


        data['x'].push(x);
        data['y'].push(y);
        data['width'].push(width);
        data['height'].push(height);


        source.trigger('change');
    """)

box_select = BoxSelectTool(callback=callback)

p = figure(plot_width=400,
           plot_height=400,
           tools=[box_select],
           title="Select Below",
           x_range=Range1d(start=0.0, end=1.0),
           y_range=Range1d(start=0.0, end=1.0))


rect = Rect(x='x',
            y='y',
            width='width',
            height='height',
            fill_alpha=0.3,
            fill_color='#009933')


p.add_glyph(source, rect, selection_glyph=rect, nonselection_glyph=rect, name="selectionbox")

session = push_session(curdoc())

def toolEventsCallback(attr, old, new):
    print("callback", new)
    x0 = new[0]['x0']
    x1 = new[0]['x1']
    print("x0=%f  x1=%f" % (x0, x1))

p.tool_events.on_change("geometries", toolEventsCallback)

session.show() 
session.loop_until_closed() 

At least in Bokeh 0.11.1 there are no events send back to Python for the ColumnDataSource.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!