How can I return the index of the scatter using js callback?

41 views Asked by At

I am trying to create a JS callback to return the index of the scatter I created. But seems like the output is always “undefined”. Could anyone help me what is wrong with my code?

here is a short example:

from bokeh.models import ColumnDataSource, CustomJS
from bokeh.plotting import figure, output_file, show
from bokeh.plotting import figure


# create some data
source = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5],
                                    y=[6, 7, 8, 9, 10],color=["navy", "orange", "olive", "firebrick", "gold"]))

# create a plot with circles
plot = figure()
plot.circle('x', 'y', size=10, source=source, color = 'color')

# create the JavaScript callback
callback = CustomJS(args=dict(source=source), code="""  
    
    // get the index of the selected point
    var index = source.selected.indices[0];
    
    // alert the index
    alert(index);
""")

# add the callback to the plot
plot.js_on_event('tap', callback)

# show the plot
show(plot)
1

There are 1 answers

0
mosc9575 On

You have to evaluate the callback object cb_obj to get information about the pan action.

callback = CustomJS(args=dict(source=source), code="""
    console.log(cb_obj['x'], cb_obj['y']);
    // alert(cb_obj['x'], cb_obj['y']);
""")

Be careful, because this will not return the position of the circle renederer. This will return the position of the click event. This event will also be triggered if no renderer is close to the click.