光标演示

此示例显示如何使用matplotlib提供数据游标。 它使用matplotlib来绘制光标并且可能很慢,因为这需要在每次鼠标移动时重新绘制图形。

使用本机GUI绘图可以更快地进行镜像,就像在wxcursor_demo.py中一样。

mpldatacursor和mplcursors第三方包可用于实现类似的效果。参看这个:

https://github.com/joferkington/mpldatacursor https://github.com/anntzer/mplcursors

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. class Cursor(object):
  4. def __init__(self, ax):
  5. self.ax = ax
  6. self.lx = ax.axhline(color='k') # the horiz line
  7. self.ly = ax.axvline(color='k') # the vert line
  8. # text location in axes coords
  9. self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
  10. def mouse_move(self, event):
  11. if not event.inaxes:
  12. return
  13. x, y = event.xdata, event.ydata
  14. # update the line positions
  15. self.lx.set_ydata(y)
  16. self.ly.set_xdata(x)
  17. self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
  18. plt.draw()
  19. class SnaptoCursor(object):
  20. """
  21. Like Cursor but the crosshair snaps to the nearest x,y point
  22. For simplicity, I'm assuming x is sorted
  23. """
  24. def __init__(self, ax, x, y):
  25. self.ax = ax
  26. self.lx = ax.axhline(color='k') # the horiz line
  27. self.ly = ax.axvline(color='k') # the vert line
  28. self.x = x
  29. self.y = y
  30. # text location in axes coords
  31. self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
  32. def mouse_move(self, event):
  33. if not event.inaxes:
  34. return
  35. x, y = event.xdata, event.ydata
  36. indx = min(np.searchsorted(self.x, [x])[0], len(self.x) - 1)
  37. x = self.x[indx]
  38. y = self.y[indx]
  39. # update the line positions
  40. self.lx.set_ydata(y)
  41. self.ly.set_xdata(x)
  42. self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
  43. print('x=%1.2f, y=%1.2f' % (x, y))
  44. plt.draw()
  45. t = np.arange(0.0, 1.0, 0.01)
  46. s = np.sin(2 * 2 * np.pi * t)
  47. fig, ax = plt.subplots()
  48. # cursor = Cursor(ax)
  49. cursor = SnaptoCursor(ax, t, s)
  50. plt.connect('motion_notify_event', cursor.mouse_move)
  51. ax.plot(t, s, 'o')
  52. plt.axis([0, 1, -1, 1])
  53. plt.show()

下载这个示例