Bokeh: CustomJS Callback for Mouse Move or Click

穿精又带淫゛_ 提交于 2019-12-04 15:42:59

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
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!