|
1 | 1 | from pylab import figure, show, nx |
| 2 | +import matplotlib.transforms as transforms |
2 | 3 | from matplotlib.patches import RegularPolygon |
3 | 4 | import matplotlib.agg as agg |
4 | 5 |
|
5 | | -fig = figure(figsize=(8,8)) |
6 | | -ax = fig.add_subplot(111, aspect='equal') |
7 | | -t = nx.arange(0.0, 4.0, 0.01) |
8 | | -s = 2*nx.sin(2*nx.pi*8*t) |
9 | | -line, = ax.plot(t, s) |
10 | | -line2, = ax.plot(t, 0.5*s, '--') |
11 | 6 |
|
| 7 | +class ClipWindow: |
| 8 | + def __init__(self, ax, line): |
| 9 | + self.ax = ax |
| 10 | + ax.set_title('drag polygon around to test clipping') |
| 11 | + self.canvas = ax.figure.canvas |
| 12 | + self.line = line |
| 13 | + self.poly = RegularPolygon( |
| 14 | + (200, 200), numVertices=10, radius=100, |
| 15 | + facecolor='yellow', alpha=0.25, |
| 16 | + transform=transforms.identity_transform()) |
| 17 | + |
| 18 | + ax.add_patch(self.poly) |
| 19 | + self.canvas.mpl_connect('button_press_event', self.onpress) |
| 20 | + self.canvas.mpl_connect('button_release_event', self.onrelease) |
| 21 | + self.canvas.mpl_connect('motion_notify_event', self.onmove) |
| 22 | + self.x, self.y = None, None |
| 23 | + |
| 24 | + |
| 25 | + def onpress(self, event): |
| 26 | + self.x, self.y = event.x, event.y |
| 27 | + |
| 28 | + def onrelease(self, event): |
| 29 | + self.x, self.y = None, None |
12 | 30 |
|
| 31 | + def onmove(self, event): |
13 | 32 |
|
14 | | -markers, = ax.plot(t, 2*(nx.mlab.rand(len(t))-0.5), 'bo') |
15 | | -path = agg.path_storage() |
16 | | -poly = RegularPolygon( (2, 0.), numVertices=100, radius=1.5, |
17 | | - facecolor='yellow', alpha=0.25) |
| 33 | + if self.x is None: return |
| 34 | + dx = event.x - self.x |
| 35 | + dy = event.y - self.y |
| 36 | + self.x, self.y = event.x, event.y |
| 37 | + x, y = self.poly.xy |
| 38 | + x += dx |
| 39 | + y += dy |
| 40 | + #print self.y, event.y, dy, y |
| 41 | + self.poly.xy = x,y |
| 42 | + self._clip() |
| 43 | + |
| 44 | + def _clip(self): |
| 45 | + fig = self.ax.figure |
| 46 | + l,b,w,h = fig.bbox.get_bounds() |
| 47 | + path = agg.path_storage() |
| 48 | + |
| 49 | + for i, xy in enumerate(self.poly.get_verts()): |
| 50 | + x,y = xy |
| 51 | + y = h-y |
| 52 | + if i==0: path.move_to(x,y) |
| 53 | + else: path.line_to(x,y) |
| 54 | + path.close_polygon() |
| 55 | + self.line.set_clip_path(path) |
| 56 | + self.canvas.draw_idle() |
| 57 | + |
| 58 | + |
| 59 | +fig = figure(figsize=(8,8)) |
| 60 | +ax = fig.add_subplot(111) |
| 61 | +t = nx.arange(0.0, 4.0, 0.01) |
| 62 | +s = 2*nx.sin(2*nx.pi*8*t) |
18 | 63 |
|
19 | | -ax.add_patch(poly) |
20 | | -for i, xy in enumerate(ax.transData.seq_xy_tups(poly.get_verts())): |
21 | | - if i==0: path.move_to(*xy) |
22 | | - else: path.line_to(*xy) |
23 | | -path.close_polygon() |
24 | | -line.set_clip_path(path) |
25 | | -line2.set_clip_path(path) |
| 64 | +line, = ax.plot(t, 2*(nx.mlab.rand(len(t))-0.5), 'b-') |
| 65 | +clipwin = ClipWindow(ax, line) |
26 | 66 | show() |
0 commit comments