In a Databricks notebook, I am plotting a curve using bokeh. I want the user to be able to hover their cursor over the graph, have it snap to the curve, and then - via mouse click - have the ability to print data (x,y) for the point on the curve that their cursor has snapped to.
As you'll see below, I'm halfway there. The hovertool allows the user's cursor to snap to the curve, and the JS callback will print the data (x,y) at the cursor's location on the graph upon mouse clicks. The problem is that I want the (x,y) printed to correspond not to the cursor's location (which it currently is doing), but the location on the curve which the hovertool is snapping to. Is it possible to get that information from the hover tool to the event callback?
import bokeh.embed as bembed
from bokeh import events
from bokeh.io import output_file
from bokeh.layouts import row
from bokeh.models import CustomJS, Div
from bokeh.plotting import figure
from bokeh.models import HoverTool
from bokeh.resources import CDN
def display_event(div, attributes=[], style = 'float:left;clear:left;font_size=13px'):
return CustomJS(args=dict(div=div), code="""
const attrs = %s;
const args = [];
for (let i = 0; i<attrs.length; i++) {
args.push(attrs[i] + '=' + Number(cb_obj[attrs[i]]).toFixed(2));
}
const line = "<span style=%r><b>" + cb_obj.event_name + "</b>(" + args.join(", ") + ")</span>\\n";
const text = div.text.concat(line);
const lines = text.split("\\n")
if (lines.length > 35)
lines.shift();
div.text = lines.join("\\n");
""" % (attributes, style))
x = [0, 1, 2]
y = [0, 1, 2]
p = figure()
p.line(x, y)
hover = HoverTool(tooltips=[
("(x, y)", "(@x, @y)")
])
hover.point_policy='snap_to_data'
p.add_tools(hover)
div = Div(width=400, height=p.height, height_policy="fixed")
layout = row(p, div)
point_attributes = ['x', 'y']
p.js_on_event(events.Tap, display_event(div, attributes=point_attributes))
displayHTML(bembed.file_html(layout, CDN))