|
12 | 12 |
|
13 | 13 | You can copy and paste individual parts, or download the entire example |
14 | 14 | using the link at the bottom of the page. |
| 15 | +
|
| 16 | +The example illustrates how to connect a function to the scroll wheel event. |
15 | 17 | """ |
16 | 18 |
|
17 | 19 | import numpy as np |
18 | 20 | import matplotlib.pyplot as plt |
19 | 21 |
|
20 | 22 |
|
21 | | -# Fixing random state for reproducibility |
22 | | -np.random.seed(19680801) |
23 | | - |
24 | | - |
25 | 23 | class IndexTracker: |
26 | 24 | def __init__(self, ax, X): |
27 | | - self.ax = ax |
28 | | - ax.set_title('use scroll wheel to navigate images') |
29 | | - |
| 25 | + self.index = 0 |
30 | 26 | 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]) |
| 27 | + self.ax = ax |
| 28 | + self.im = ax.imshow(self.X[:, :, self.index]) |
35 | 29 | self.update() |
36 | 30 |
|
37 | 31 | def on_scroll(self, event): |
38 | | - print("%s %s" % (event.button, event.step)) |
39 | | - if event.button == 'up': |
40 | | - self.ind = (self.ind + 1) % self.slices |
41 | | - else: |
42 | | - self.ind = (self.ind - 1) % self.slices |
| 32 | + print(event.button, event.step) |
| 33 | + increment = 1 if event.button == 'up' else -1 |
| 34 | + max_index = self.X.shape[-1] - 1 |
| 35 | + self.index = np.clip(self.index + increment, 0, max_index) |
43 | 36 | self.update() |
44 | 37 |
|
45 | 38 | def update(self): |
46 | | - self.im.set_data(self.X[:, :, self.ind]) |
47 | | - self.ax.set_ylabel('slice %s' % self.ind) |
| 39 | + self.im.set_data(self.X[:, :, self.index]) |
| 40 | + self.ax.set_title( |
| 41 | + f'Use scroll wheel to navigate\nimage {self.index}') |
48 | 42 | self.im.axes.figure.canvas.draw() |
49 | 43 |
|
50 | 44 |
|
51 | | -fig, ax = plt.subplots(1, 1) |
52 | | - |
53 | | -X = np.random.rand(20, 20, 40) |
| 45 | +x, y, z = np.ogrid[-10:10:100j, -10:10:100j, 1:10:20j] |
| 46 | +X = np.sin(x * y * z) / (x * y * z) |
54 | 47 |
|
| 48 | +fig, ax = plt.subplots() |
| 49 | +# create an IndexTracker and make sure it lives during the whole |
| 50 | +# lifetime of the figure by assigning it to a variable |
55 | 51 | tracker = IndexTracker(ax, X) |
56 | 52 |
|
57 | | - |
58 | 53 | fig.canvas.mpl_connect('scroll_event', tracker.on_scroll) |
59 | 54 | plt.show() |
0 commit comments