You are reading an old version of the documentation (v2.1.1). For the latest version see https://matplotlib.org/stable/
matplotlib
Fork me on GitHub


Travis-CI:

Related Topics

This Page

Image Slices ViewerΒΆ

Scroll through 2D image slices of a 3D array.

../../_images/sphx_glr_image_slices_viewer_001.png
from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt


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

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

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

    def onscroll(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
        self.update()

    def update(self):
        self.im.set_data(self.X[:, :, self.ind])
        ax.set_ylabel('slice %s' % self.ind)
        self.im.axes.figure.canvas.draw()


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

X = np.random.rand(20, 20, 40)

tracker = IndexTracker(ax, X)


fig.canvas.mpl_connect('scroll_event', tracker.onscroll)
plt.show()

Total running time of the script: ( 0 minutes 0.044 seconds)

Gallery generated by Sphinx-Gallery