|
1 | 1 | """ |
2 | | -=================== |
3 | | -Image Slices Viewer |
4 | | -=================== |
| 2 | +============ |
| 3 | +Scroll event |
| 4 | +============ |
5 | 5 |
|
6 | | -Scroll through 2D image slices of a 3D array. |
| 6 | +In this example a scroll wheel event is used to scroll through 2D slices of |
| 7 | +3D data. |
7 | 8 |
|
8 | 9 | .. note:: |
9 | 10 | This example exercises the interactive capabilities of Matplotlib, and this |
|
18 | 19 | importmatplotlib.pyplotasplt |
19 | 20 |
|
20 | 21 |
|
21 | | -# Fixing random state for reproducibility |
22 | | -np.random.seed(19680801) |
23 | | - |
24 | | - |
25 | 22 | classIndexTracker: |
26 | 23 | def__init__(self,ax,X): |
27 | | -self.ax=ax |
28 | | -ax.set_title('use scroll wheel to navigate images') |
29 | | - |
| 24 | +self.index=0 |
30 | 25 | self.X=X |
31 | | -rows,cols,self.slices=X.shape |
32 | | -self.ind=self.slices//2 |
33 | | - |
34 | | -self.im=ax.imshow(self.X[:, :,self.ind]) |
| 26 | +self.ax=ax |
| 27 | +self.im=ax.imshow(self.X[:, :,self.index]) |
35 | 28 | self.update() |
36 | 29 |
|
37 | 30 | defon_scroll(self,event): |
38 | | -print("%s %s"% (event.button,event.step)) |
39 | | -ifevent.button=='up': |
40 | | -self.ind= (self.ind+1)%self.slices |
41 | | -else: |
42 | | -self.ind= (self.ind-1)%self.slices |
| 31 | +print(event.button,event.step) |
| 32 | +increment=1ifevent.button=='up'else-1 |
| 33 | +max_index=self.X.shape[-1]-1 |
| 34 | +self.index=np.clip(self.index+increment,0,max_index) |
43 | 35 | self.update() |
44 | 36 |
|
45 | 37 | defupdate(self): |
46 | | -self.im.set_data(self.X[:, :,self.ind]) |
47 | | -self.ax.set_ylabel('slice %s'%self.ind) |
| 38 | +self.im.set_data(self.X[:, :,self.index]) |
| 39 | +self.ax.set_title( |
| 40 | +f'Use scroll wheel to navigate\nindex{self.index}') |
48 | 41 | self.im.axes.figure.canvas.draw() |
49 | 42 |
|
50 | 43 |
|
51 | | -fig,ax=plt.subplots(1,1) |
52 | | - |
53 | | -X=np.random.rand(20,20,40) |
| 44 | +x,y,z=np.ogrid[-10:10:100j,-10:10:100j,1:10:20j] |
| 45 | +X=np.sin(x*y*z)/ (x*y*z) |
54 | 46 |
|
| 47 | +fig,ax=plt.subplots() |
| 48 | +# create an IndexTracker and make sure it lives during the whole |
| 49 | +# lifetime of the figure by assigning it to a variable |
55 | 50 | tracker=IndexTracker(ax,X) |
56 | 51 |
|
57 | | - |
58 | 52 | fig.canvas.mpl_connect('scroll_event',tracker.on_scroll) |
59 | 53 | plt.show() |