套索选择器演示

使用套索工具以交互方式选择数据点。

此示例绘制散点图。 然后,您可以通过在图表上的点周围绘制套索循环来选择几个点。 要绘制,只需单击图形,按住,然后将其拖动到需要选择的点周围。

  1. import numpy as np
  2. from matplotlib.widgets import LassoSelector
  3. from matplotlib.path import Path
  4. class SelectFromCollection(object):
  5. """Select indices from a matplotlib collection using `LassoSelector`.
  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.lasso = LassoSelector(ax, onselect=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.lasso.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. # Fixing random state for reproducibility
  51. np.random.seed(19680801)
  52. data = np.random.rand(100, 2)
  53. subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
  54. fig, ax = plt.subplots(subplot_kw=subplot_kw)
  55. pts = ax.scatter(data[:, 0], data[:, 1], s=80)
  56. selector = SelectFromCollection(ax, pts)
  57. def accept(event):
  58. if event.key == "enter":
  59. print("Selected points:")
  60. print(selector.xys[selector.ind])
  61. selector.disconnect()
  62. ax.set_title("")
  63. fig.canvas.draw()
  64. fig.canvas.mpl_connect("key_press_event", accept)
  65. ax.set_title("Press enter to accept selected points.")
  66. plt.show()

下载这个示例