套索演示

演示如何使用套索选择一组点并获取所选点的索引。回调用于更改所选点的颜色。

这是一个概念验证实现(尽管它可以按原样使用)。将对API进行一些改进。

套索演示

  1. from matplotlib import colors as mcolors, path
  2. from matplotlib.collections import RegularPolyCollection
  3. import matplotlib.pyplot as plt
  4. from matplotlib.widgets import Lasso
  5. import numpy as np
  6. class Datum(object):
  7. colorin = mcolors.to_rgba("red")
  8. colorout = mcolors.to_rgba("blue")
  9. def __init__(self, x, y, include=False):
  10. self.x = x
  11. self.y = y
  12. if include:
  13. self.color = self.colorin
  14. else:
  15. self.color = self.colorout
  16. class LassoManager(object):
  17. def __init__(self, ax, data):
  18. self.axes = ax
  19. self.canvas = ax.figure.canvas
  20. self.data = data
  21. self.Nxy = len(data)
  22. facecolors = [d.color for d in data]
  23. self.xys = [(d.x, d.y) for d in data]
  24. self.collection = RegularPolyCollection(
  25. 6, sizes=(100,),
  26. facecolors=facecolors,
  27. offsets=self.xys,
  28. transOffset=ax.transData)
  29. ax.add_collection(self.collection)
  30. self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
  31. def callback(self, verts):
  32. facecolors = self.collection.get_facecolors()
  33. p = path.Path(verts)
  34. ind = p.contains_points(self.xys)
  35. for i in range(len(self.xys)):
  36. if ind[i]:
  37. facecolors[i] = Datum.colorin
  38. else:
  39. facecolors[i] = Datum.colorout
  40. self.canvas.draw_idle()
  41. self.canvas.widgetlock.release(self.lasso)
  42. del self.lasso
  43. def onpress(self, event):
  44. if self.canvas.widgetlock.locked():
  45. return
  46. if event.inaxes is None:
  47. return
  48. self.lasso = Lasso(event.inaxes,
  49. (event.xdata, event.ydata),
  50. self.callback)
  51. # acquire a lock on the widget drawing
  52. self.canvas.widgetlock(self.lasso)
  53. if __name__ == '__main__':
  54. np.random.seed(19680801)
  55. data = [Datum(*xy) for xy in np.random.rand(100, 2)]
  56. ax = plt.axes(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
  57. ax.set_title('Lasso points using left mouse button')
  58. lman = LassoManager(ax, data)
  59. plt.show()

下载这个示例