Matplotlib 스크롤 이벤트

Beginner

This tutorial is from open-source community. Access the source code

소개

이 랩에서는 Matplotlib 에서 스크롤 이벤트를 사용하는 방법을 단계별로 안내합니다. 스크롤 이벤트는 3D 데이터의 2D 슬라이스를 탐색하는 데 사용할 수 있습니다.

VM 팁

VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접속하십시오.

때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.

학습 중 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.

필요한 라이브러리 임포트

먼저, Matplotlib 과 NumPy 를 포함한 필요한 라이브러리를 임포트해야 합니다.

import matplotlib.pyplot as plt
import numpy as np

데이터 생성

NumPy 의 ogrid 함수를 사용하여 3D 데이터를 생성합니다.

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

IndexTracker 클래스 생성

IndexTracker 클래스는 현재 슬라이스 인덱스를 추적하고 이에 따라 플롯을 업데이트합니다.

class IndexTracker:
    def __init__(self, ax, X):
        self.index = 0
        self.X = X
        self.ax = ax
        self.im = ax.imshow(self.X[:, :, self.index])
        self.update()

    def on_scroll(self, event):
        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.index])
        self.ax.set_title(
            f'Use scroll wheel to navigate\nindex {self.index}')
        self.im.axes.figure.canvas.draw()

플롯 생성 및 스크롤 이벤트 연결

Matplotlib 의 subplots 함수를 사용하여 플롯을 생성하고 생성된 IndexTracker 객체를 전달합니다. 그런 다음 mpl_connect를 사용하여 스크롤 이벤트를 figure canvas 에 연결합니다.

fig, ax = plt.subplots()
tracker = IndexTracker(ax, X)

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

요약

이 랩에서는 Matplotlib 에서 스크롤 이벤트를 사용하여 3D 데이터의 2D 슬라이스를 탐색하는 방법을 배웠습니다. 현재 슬라이스 인덱스를 추적하고 이에 따라 플롯을 업데이트하기 위해 IndexTracker 클래스를 생성했습니다. 마지막으로, 플롯을 생성하고 스크롤 이벤트를 figure canvas 에 연결했습니다.