矩形选择器

在某处鼠标点击,将鼠标移动到某个目的地,然后释放按钮。 此类提供单击和释放事件,并从点击点到实际鼠标位置(在相同轴内)绘制一条线或一个框,直到释放按钮。 在方法’self.ignore()’中,检查来自eventpress和eventrelease的按钮是否相同。

矩形选择器示例

输出:

  1. click --> release
  1. from matplotlib.widgets import RectangleSelector
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. def line_select_callback(eclick, erelease):
  5. 'eclick and erelease are the press and release events'
  6. x1, y1 = eclick.xdata, eclick.ydata
  7. x2, y2 = erelease.xdata, erelease.ydata
  8. print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (x1, y1, x2, y2))
  9. print(" The button you used were: %s %s" % (eclick.button, erelease.button))
  10. def toggle_selector(event):
  11. print(' Key pressed.')
  12. if event.key in ['Q', 'q'] and toggle_selector.RS.active:
  13. print(' RectangleSelector deactivated.')
  14. toggle_selector.RS.set_active(False)
  15. if event.key in ['A', 'a'] and not toggle_selector.RS.active:
  16. print(' RectangleSelector activated.')
  17. toggle_selector.RS.set_active(True)
  18. fig, current_ax = plt.subplots() # make a new plotting range
  19. N = 100000 # If N is large one can see
  20. x = np.linspace(0.0, 10.0, N) # improvement by use blitting!
  21. plt.plot(x, +np.sin(.2*np.pi*x), lw=3.5, c='b', alpha=.7) # plot something
  22. plt.plot(x, +np.cos(.2*np.pi*x), lw=3.5, c='r', alpha=.5)
  23. plt.plot(x, -np.sin(.2*np.pi*x), lw=3.5, c='g', alpha=.3)
  24. print("\n click --> release")
  25. # drawtype is 'box' or 'line' or 'none'
  26. toggle_selector.RS = RectangleSelector(current_ax, line_select_callback,
  27. drawtype='box', useblit=True,
  28. button=[1, 3], # don't use middle button
  29. minspanx=5, minspany=5,
  30. spancoords='pixels',
  31. interactive=True)
  32. plt.connect('key_press_event', toggle_selector)
  33. plt.show()

下载这个示例