Record data points clicked in bokeh plot

I’m trying to get a list of the points that have been clicked on a graph, but i’m getting an empty list each time. The purpose of this is to allow my colleagues to click on interested data points on a graph, and for the clicked points to be recorded for other work.

I am modifying code from the Chemplot python module: Line tha creates plot with colourmap:

circle_plot = p.circle(x=x, y=y, size=2.5, alpha=0.8, line_color=index_cmap, fill_color=index_cmap,
                     source=df_data)
                color_bar = ColorBar(color_mapper=color_mapper, location=(0,0))
                p.add_layout(color_bar, 'right')

Part that I have added to get the list of datapoints:

                taptool = TapTool(renderers=[circle_plot])
                p.add_tools(taptool)    

                
                code = """
                var inds = source.selected.indices;
                var d1 = source.data;
                var indices = [];
                
                for (var i = 0; i < inds.length; i++) {
                    indices.push(d1['index'][inds[i]]);
                }
                
                console.log(indices);
                """
            
                # Convert the DataFrame to a ColumnDataSource
                source = ColumnDataSource(df_data)
                
                # Then pass the ColumnDataSource into the CustomJS callback
                callback = CustomJS(args=dict(source=source), code=code)

                
                # Associate the callback with taptool
                taptool.callback = callback

Instead of returning the datapoints indices it returns a blank array.

Note: Same question has been posted to stackoverflow but only has had 5 views so far :Record datapoints clicked in bokeh plot - Stack Overflow

If you want to access and respond to selections, then you should do it as described here in the docs section CustomJS for Selections. The TapTool.callback API is historical at this point, and does something a bit different (it may be deprecated and removed entirely in future releases).

1 Like

Thank you Byran, that helped a lot. I got it working using the info in the link you sent

1 Like