1
votes

Does anyone know how to pass a variable from bokehjs callback function to python? I'm developing a web app using flask framework and I'm trying to select several points from bokeh plot on my web app and get the x,y coordinates. I want my select_points function below to return those coordinates, and use the variable outside of that function (on my main code). Please help me.

def select_points(data_x, svg_y):
    from bokeh.models import CustomJS, ColumnDataSource, TapTool
    from bokeh.plotting import figure
    from bokeh.embed import components

    source = ColumnDataSource(data=dict(x=data_x, y=svg_y))

    source2 = ColumnDataSource(data = dict(x = [], y = []))

    callback = source.selected.js_on_change('indices', CustomJS(args=dict(source=source, source2=source2), code="""
        var inds = cb_obj.indices;
        var d1 = source.data;
        var d2 = source2.data;
        d2['x'] = []
        d2['y'] = []
        for (var i = 0; i < inds.length; i++) {
            d2['x'].push(d1['x'][inds[i]])
            d2['y'].push(d1['y'][inds[i]])
        }
        source2.data = d2
    """)
    )

    taptool = TapTool(callback=callback)
    p = figure(tools=[taptool], title="Press shift + cursor click 10 times to select data points")
    p.circle('x', 'y', source=source, alpha=0.6)

    script, div = components(p)
    select_points.kwargs = {'script': script, 'div': div}
    select_points.kwargs['title'] = 'bokeh-with-flask'

    return source2.data['x'], source2.data['y']