Hi,
In the example below I can make the cursor snap over the
nearest point with the mouse and also move the cursor with the
keyboard.
But I can’t print the coordinates in the toolbar when the I
move the cursor with the keyboard as when I move with the mouse!
Does anyone have an idea?
Cheers,
Alexandre
from pylab import *
import numpy
from matplotlib.widgets import Cursor
class DataCursor(Cursor):
def init(self, t, y, ax, useblit=True, **lineprops):
Cursor.init(self, ax, useblit=True, **lineprops)
self.y = y
self.t = t
self.i = 0
self.xstr = ‘’
self.ystr = ‘’
def onmove(self, event):
"""
we override event.xdata to force it to snap-to nearest data item
"""
N = len(self.y)
# Mouse Move
if event.name=="motion_notify_event":
xdata = event.xdata
ind = numpy.searchsorted(self.t, xdata)
self.i = min(N-1, ind)
# Key press
elif event.name=="key_press_event":
if event.key=="right":
self.i+=1
while self.i>=N:
self.i-=N
elif event.key=="left":
self.i-=1
while self.i<0:
self.i+=N
# Set the cursor and draw
event.xdata = self.t[self.i]
event.ydata = self.y[self.i]
self.xstr = '%1.3f'%event.xdata
self.ystr = '%1.3f'%event.ydata
Cursor.onmove(self, event)
def fmtx(self, x):
return self.xstr
def fmty(self, y):
return self.ystr
t = numpy.cumsum(numpy.random.rand(20))
y = numpy.random.rand(len(t))
fig = figure()
ax = fig.add_subplot(111)
ax.plot(t, y, ‘go’)
cursor = DataCursor(t, y, ax, useblit=True, color=‘red’, linewidth=2 )
ax.fmt_xdata = cursor.fmtx
ax.fmt_ydata = cursor.fmty
fig.canvas.mpl_connect(‘key_press_event’, cursor.onmove )
show()