Skip to content

Commit

Permalink
Merge pull request #24366 from timhoffm/doc-image-slice-viewer
Browse files Browse the repository at this point in the history
DOC: Improve Image Slices Viewer example
  • Loading branch information
tacaswell committed Nov 6, 2022
2 parents 11147a7 + fbca556 commit 1685cb4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 26 deletions.
46 changes: 20 additions & 26 deletions examples/event_handling/image_slices_viewer.py
@@ -1,9 +1,10 @@
"""
===================
Image Slices Viewer
===================
============
Scroll event
============
Scroll through 2D image slices of a 3D array.
In this example a scroll wheel event is used to scroll through 2D slices of
3D data.
.. note::
This example exercises the interactive capabilities of Matplotlib, and this
Expand All @@ -18,42 +19,35 @@
import matplotlib.pyplot as plt


# Fixing random state for reproducibility
np.random.seed(19680801)


class IndexTracker:
def __init__(self, ax, X):
self.ax = ax
ax.set_title('use scroll wheel to navigate images')

self.index = 0
self.X = X
rows, cols, self.slices = X.shape
self.ind = self.slices//2

self.im = ax.imshow(self.X[:, :, self.ind])
self.ax = ax
self.im = ax.imshow(self.X[:, :, self.index])
self.update()

def on_scroll(self, event):
print("%s %s" % (event.button, event.step))
if event.button == 'up':
self.ind = (self.ind + 1) % self.slices
else:
self.ind = (self.ind - 1) % self.slices
print(event.button, event.step)
increment = 1 if event.button == 'up' else -1
max_index = self.X.shape[-1] - 1
self.index = np.clip(self.index + increment, 0, max_index)
self.update()

def update(self):
self.im.set_data(self.X[:, :, self.ind])
self.ax.set_ylabel('slice %s' % self.ind)
self.im.set_data(self.X[:, :, self.index])
self.ax.set_title(
f'Use scroll wheel to navigate\nindex {self.index}')
self.im.axes.figure.canvas.draw()


fig, ax = plt.subplots(1, 1)

X = np.random.rand(20, 20, 40)
x, y, z = np.ogrid[-10:10:100j, -10:10:100j, 1:10:20j]
X = np.sin(x * y * z) / (x * y * z)

fig, ax = plt.subplots()
# create an IndexTracker and make sure it lives during the whole
# lifetime of the figure by assigning it to a variable
tracker = IndexTracker(ax, X)


fig.canvas.mpl_connect('scroll_event', tracker.on_scroll)
plt.show()
8 changes: 8 additions & 0 deletions lib/matplotlib/backend_bases.py
Expand Up @@ -2440,6 +2440,14 @@ def func(event: Event) -> Any
be set to the mouse location in data coordinates. See `.KeyEvent`
and `.MouseEvent` for more info.
.. note::
If func is a method, this only stores a weak reference to the
method. Thus, the figure does not influence the lifetime of
the associated object. Usually, you want to make sure that the
object is kept alive throughout the lifetime of the figure by
holding a reference to it.
Returns
-------
cid
Expand Down

0 comments on commit 1685cb4

Please sign in to comment.