问题
I want to update my plot data based on the current mouse position.
What I'm aiming for is something like the interactive power function plot, but instead of taking the exponent from a slider, take the exponent to be the current x-value of the mouse cursor (in plot coordinate space, not display coordinates).
If it's not possible to get an onMouseMove callback, onClick would also be ok. However, I don't want to have to click a specific graph (then I could use TapTool), but tapping anywhere in the plot should suffice.
回答1:
You can use HoverTool and CustomJS as in the code example below. This example plots a line from the cursor position to the (1,1) point. When opening a JavaScript Console, you can see the values of x and y as you move the mouse.
from bokeh.plotting import figure,show, ColumnDataSource
from bokeh.models import CustomJS, HoverTool
import numpy as np
s = ColumnDataSource(data = dict(x=[0,1],y=[0,1])) #points of the line
callback = CustomJS(args=dict(s=s), code="""
var geometry = cb_data['geometry'];
var x_data = geometry.x; // current mouse x position in plot coordinates
var y_data = geometry.y; // current mouse y position in plot coordinates
console.log("(x,y)=" + x_data+","+y_data); //monitors values in Javascript console
var x = s.get('data')['x'];
var y = s.get('data')['y'];
x[0] = x_data;
y[0] = y_data;
s.trigger('change');
""")
hover_tool = HoverTool(callback=callback)
p = figure(x_range=(0,1), y_range=(0,1), tools= [hover_tool,
"crosshair,box_zoom,wheel_zoom,pan,reset"])
p.line(x='x',y='y',source=s)
show(p)
Output of the Javascript console:
...
VM615:7 (x,y)=0.37494791666666666,0.37447916666666664
VM615:7 (x,y)=0.37494791666666666,0.37114583333333334
VM615:7 (x,y)=0.37161458333333336,0.37114583333333334
VM615:7 (x,y)=0.38828125,0.37114583333333334
VM615:7 (x,y)=0.43161458333333336,0.3878125
VM615:7 (x,y)=0.7216145833333333,0.4878125
...
来源:https://stackoverflow.com/questions/34896606/bokeh-customjs-callback-for-mouse-move-or-click