|
| 1 | +import numpy as np |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +import matplotlib.patches as patches |
| 4 | +x, y = np.random.rand(2, 200) |
| 5 | + |
| 6 | +fig = plt.figure() |
| 7 | +ax = fig.add_subplot(111) |
| 8 | +circ = patches.Circle( (0.5, 0.5), 0.25, alpha=0.8, fc='yellow') |
| 9 | +ax.add_patch(circ) |
| 10 | + |
| 11 | + |
| 12 | +ax.plot(x, y, alpha=0.2) |
| 13 | +line, = ax.plot(x, y, alpha=1.0, clip_path=circ) |
| 14 | + |
| 15 | +class EventHandler: |
| 16 | + def __init__(self): |
| 17 | + fig.canvas.mpl_connect('button_press_event', self.onpress) |
| 18 | + fig.canvas.mpl_connect('button_release_event', self.onrelease) |
| 19 | + fig.canvas.mpl_connect('motion_notify_event', self.onmove) |
| 20 | + self.x0, self.y0 = circ.center |
| 21 | + self.pressevent = None |
| 22 | + |
| 23 | + def onpress(self, event): |
| 24 | + if event.inaxes!=ax: |
| 25 | + return |
| 26 | + |
| 27 | + if not circ.contains(event): |
| 28 | + return |
| 29 | + |
| 30 | + self.pressevent = event |
| 31 | + |
| 32 | + def onrelease(self, event): |
| 33 | + self.pressevent = None |
| 34 | + self.x0, self.y0 = circ.center |
| 35 | + |
| 36 | + def onmove(self, event): |
| 37 | + if self.pressevent is None or event.inaxes!=self.pressevent.inaxes: |
| 38 | + return |
| 39 | + |
| 40 | + dx = event.xdata - self.pressevent.xdata |
| 41 | + dy = event.ydata - self.pressevent.ydata |
| 42 | + circ.center = self.x0 + dx, self.y0 + dy |
| 43 | + line.set_clip_path(circ) |
| 44 | + fig.canvas.draw() |
| 45 | + |
| 46 | +handler = EventHandler() |
| 47 | +plt.show() |
0 commit comments