1

I want to get the mouse position in a plot via a callback function using bokeh server. A solution for the latest bokeh version 2.0.2 would be great.

So far I found this old solution which does not work any more due to deprecation of the tool_events attribute in the figure object.

I have found this javascript example which does not work for the boekh server context.

Has someone an idea how to achieve this with bokeh?

sehan2
  • 1,700
  • 1
  • 10
  • 23
  • 1
    Related - I needed to do this in `holoviews` with a `bokeh` backend, here's how I did it: https://stackoverflow.com/a/71107256/1177832 – danwild Feb 14 '22 at 04:57

1 Answers1

4

If you want to get mouse position after every move, regardless of whether the cursor is over any glyph, you can just listen to the mousemove event:

from bokeh.events import PointEvent
from bokeh.io import curdoc
from bokeh.plotting import figure

p = figure()
p.circle(0, 0)


def on_mouse_move(event: PointEvent):
    print(event.x, event.y, event.sx, event.sy)


p.on_event('mousemove', on_mouse_move)

curdoc().add_root(p)

Also mouseenter and mouseleave may be of interest to you.

Eugene Pakhomov
  • 9,309
  • 3
  • 27
  • 53
  • How can someone save or access the coordinates? I see the coordinates in Anaconda Prompt but I do not know how I can get them in Spyder. – MOON Jul 10 '20 at 20:13
  • 1
    "How can I access" - well, you have the coordinates right there in the callback function. And I have no idea about Anaconda Prompt and Spider, I've never used them. – Eugene Pakhomov Jul 10 '20 at 20:58
  • Is there also the possibility to access the index of the datapoint one is hovering over? – Crysers Mar 19 '21 at 16:42
  • At the time of writing the answer, there was no built-in way - you had to find the index manually. I have no idea whether something has changed in more recent Bokeh versions. – Eugene Pakhomov Mar 19 '21 at 18:20