多边形选择器演示

显示如何以交互方式选择多边形的索引。

多边形选择器演示

输出:

  1. Select points in the figure by enclosing them within a polygon.
  2. Press the 'esc' key to start a new polygon.
  3. Try holding the 'shift' key to move all of the vertices.
  4. Try holding the 'ctrl' key to move a single vertex.
  5. Selected points:
  6. []
  1. import numpy as np
  2. from matplotlib.widgets import PolygonSelector
  3. from matplotlib.path import Path
  4. class SelectFromCollection(object):
  5. """Select indices from a matplotlib collection using `PolygonSelector`.
  6. Selected indices are saved in the `ind` attribute. This tool fades out the
  7. points that are not part of the selection (i.e., reduces their alpha
  8. values). If your collection has alpha < 1, this tool will permanently
  9. alter the alpha values.
  10. Note that this tool selects collection objects based on their *origins*
  11. (i.e., `offsets`).
  12. Parameters
  13. ----------
  14. ax : :class:`~matplotlib.axes.Axes`
  15. Axes to interact with.
  16. collection : :class:`matplotlib.collections.Collection` subclass
  17. Collection you want to select from.
  18. alpha_other : 0 <= float <= 1
  19. To highlight a selection, this tool sets all selected points to an
  20. alpha value of 1 and non-selected points to `alpha_other`.
  21. """
  22. def __init__(self, ax, collection, alpha_other=0.3):
  23. self.canvas = ax.figure.canvas
  24. self.collection = collection
  25. self.alpha_other = alpha_other
  26. self.xys = collection.get_offsets()
  27. self.Npts = len(self.xys)
  28. # Ensure that we have separate colors for each object
  29. self.fc = collection.get_facecolors()
  30. if len(self.fc) == 0:
  31. raise ValueError('Collection must have a facecolor')
  32. elif len(self.fc) == 1:
  33. self.fc = np.tile(self.fc, (self.Npts, 1))
  34. self.poly = PolygonSelector(ax, self.onselect)
  35. self.ind = []
  36. def onselect(self, verts):
  37. path = Path(verts)
  38. self.ind = np.nonzero(path.contains_points(self.xys))[0]
  39. self.fc[:, -1] = self.alpha_other
  40. self.fc[self.ind, -1] = 1
  41. self.collection.set_facecolors(self.fc)
  42. self.canvas.draw_idle()
  43. def disconnect(self):
  44. self.poly.disconnect_events()
  45. self.fc[:, -1] = 1
  46. self.collection.set_facecolors(self.fc)
  47. self.canvas.draw_idle()
  48. if __name__ == '__main__':
  49. import matplotlib.pyplot as plt
  50. fig, ax = plt.subplots()
  51. grid_size = 5
  52. grid_x = np.tile(np.arange(grid_size), grid_size)
  53. grid_y = np.repeat(np.arange(grid_size), grid_size)
  54. pts = ax.scatter(grid_x, grid_y)
  55. selector = SelectFromCollection(ax, pts)
  56. print("Select points in the figure by enclosing them within a polygon.")
  57. print("Press the 'esc' key to start a new polygon.")
  58. print("Try holding the 'shift' key to move all of the vertices.")
  59. print("Try holding the 'ctrl' key to move a single vertex.")
  60. plt.show()
  61. selector.disconnect()
  62. # After figure is closed print the coordinates of the selected points
  63. print('\nSelected points:')
  64. print(selector.xys[selector.ind])

下载这个示例