Python Matplotlib 을 이용한 대화형 데이터 시각화

Beginner

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

소개

이 랩에서는 여러 캔버스 (canvas) 와 데이터를 상호 작용하는 방법을 안내합니다. 한 축에서 점을 선택하고 강조 표시하면 다른 축에서 해당 점의 데이터를 생성합니다. 이 랩에서는 Python Matplotlib 을 사용합니다.

VM 팁

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

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

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

라이브러리 임포트

필요한 라이브러리를 임포트하는 것으로 시작합니다.

import numpy as np
import matplotlib.pyplot as plt

데이터 생성

NumPy 를 사용하여 임의의 데이터를 생성합니다.

np.random.seed(19680801)
X = np.random.rand(100, 200)
xs = np.mean(X, axis=1)
ys = np.std(X, axis=1)

Figure 및 Axes 생성

두 개의 axes 를 가진 figure 를 생성합니다.

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

데이터 플롯

생성된 데이터를 첫 번째 axis 에 플롯합니다.

line, = ax.plot(xs, ys, 'o', picker=True, pickradius=5)

Point Browser 클래스 생성

Point browser 기능을 처리할 클래스를 생성합니다.

class PointBrowser:
    def __init__(self):
        self.lastind = 0

        self.text = ax.text(0.05, 0.95, 'selected: none',
                            transform=ax.transAxes, va='top')
        self.selected, = ax.plot([xs[0]], [ys[0]], 'o', ms=12, alpha=0.4,
                                 color='yellow', visible=False)

    def on_press(self, event):
        if self.lastind is None:
            return
        if event.key not in ('n', 'p'):
            return
        if event.key == 'n':
            inc = 1
        else:
            inc = -1

        self.lastind += inc
        self.lastind = np.clip(self.lastind, 0, len(xs) - 1)
        self.update()

    def on_pick(self, event):

        if event.artist != line:
            return True

        N = len(event.ind)
        if not N:
            return True

        ## the click locations
        x = event.mouseevent.xdata
        y = event.mouseevent.ydata

        distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
        indmin = distances.argmin()
        dataind = event.ind[indmin]

        self.lastind = dataind
        self.update()

    def update(self):
        if self.lastind is None:
            return

        dataind = self.lastind

        ax2.clear()
        ax2.plot(X[dataind])

        ax2.text(0.05, 0.9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
                 transform=ax2.transAxes, va='top')
        ax2.set_ylim(-0.5, 1.5)
        self.selected.set_visible(True)
        self.selected.set_data(xs[dataind], ys[dataind])

        self.text.set_text('selected: %d' % dataind)
        fig.canvas.draw()

이벤트 핸들러 연결

이벤트 핸들러를 figure canvas 에 연결합니다.

browser = PointBrowser()

fig.canvas.mpl_connect('pick_event', browser.on_pick)
fig.canvas.mpl_connect('key_press_event', browser.on_press)

플롯 표시

플롯을 표시합니다.

plt.show()

요약

이 랩에서는 Python Matplotlib 을 사용하여 여러 canvas 와 데이터를 상호 작용하는 방법을 배웠습니다. 점 브라우저 (point browser) 기능을 처리하는 클래스를 만들고, 상호 작용을 활성화하기 위해 이벤트 핸들러 (event handler) 를 figure canvas 에 연결했습니다.