Matplotlib 를 이용한 대화형 데이터 시각화

Beginner

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

소개

데이터 시각화에서 플롯의 특정 영역을 확대하는 것은 데이터를 더 잘 이해하고 분석하는 데 매우 유용할 수 있습니다. Python 의 인기 있는 데이터 시각화 라이브러리인 Matplotlib 은 두 개의 동일한 패널을 생성하고 오른쪽 패널을 확대하여 첫 번째 패널에 확대된 영역을 나타내는 사각형을 표시하는 방법을 제공합니다. 이 랩에서는 Matplotlib 에서 이러한 대화형 확대/축소 기능을 만드는 방법을 배웁니다.

VM 팁

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

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

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

필요한 라이브러리 가져오기

먼저 Matplotlib 과 NumPy 를 포함한 필요한 라이브러리를 가져오겠습니다.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.patches import Rectangle

UpdatingRect 클래스 생성

UpdatingRect 라는 Rectangle 의 하위 클래스를 생성합니다. 이 클래스는 Axes 인스턴스로 호출되어 사각형이 Axes 의 경계에 맞춰 모양을 업데이트하도록 합니다.

class UpdatingRect(Rectangle):
    def __call__(self, ax):
        self.set_bounds(*ax.viewLim.bounds)
        ax.figure.canvas.draw_idle()

MandelbrotDisplay 클래스 생성

확대할 때 프랙탈 집합을 다시 생성하여 세부 사항이 증가하는 것을 실제로 볼 수 있도록 MandelbrotDisplay 라는 클래스를 생성합니다. 왼쪽 패널의 상자는 확대된 영역을 표시합니다.

class MandelbrotDisplay:
    def __init__(self, h=500, w=500, niter=50, radius=2., power=2):
        self.height = h
        self.width = w
        self.niter = niter
        self.radius = radius
        self.power = power

    def compute_image(self, xstart, xend, ystart, yend):
        self.x = np.linspace(xstart, xend, self.width)
        self.y = np.linspace(ystart, yend, self.height).reshape(-1, 1)
        c = self.x + 1.0j * self.y
        threshold_time = np.zeros((self.height, self.width))
        z = np.zeros(threshold_time.shape, dtype=complex)
        mask = np.ones(threshold_time.shape, dtype=bool)
        for i in range(self.niter):
            z[mask] = z[mask]**self.power + c[mask]
            mask = (np.abs(z) < self.radius)
            threshold_time += mask
        return threshold_time

    def ax_update(self, ax):
        ax.set_autoscale_on(False)
        self.width, self.height = \
            np.round(ax.patch.get_window_extent().size).astype(int)
        vl = ax.viewLim
        extent = vl.x0, vl.x1, vl.y0, vl.y1
        im = ax.images[-1]
        im.set_data(self.compute_image(*extent))
        im.set_extent(extent)
        ax.figure.canvas.draw_idle()

플롯 생성

먼저 MandelbrotDisplay 클래스를 사용하여 이미지를 계산한 다음, subplots 를 사용하여 두 개의 동일한 패널을 생성하여 플롯을 생성합니다. imshow 를 사용하여 두 패널 모두에 이미지를 추가하고, UpdatingRect 객체를 왼쪽 패널에 추가합니다.

md = MandelbrotDisplay()
Z = md.compute_image(-2., 0.5, -1.25, 1.25)

fig1, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(Z, origin='lower',
           extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max()))
ax2.imshow(Z, origin='lower',
           extent=(md.x.min(), md.x.max(), md.y.min(), md.y.max()))

rect = UpdatingRect(
    [0, 0], 0, 0, facecolor='none', edgecolor='black', linewidth=1.0)
rect.set_bounds(*ax2.viewLim.bounds)
ax1.add_patch(rect)

확대/축소 기능 추가

xlim_changed 및 ylim_changed 이벤트를 UpdatingRect 및 MandelbrotDisplay 객체에 연결하여 확대/축소 기능을 추가합니다.

ax2.callbacks.connect('xlim_changed', rect)
ax2.callbacks.connect('ylim_changed', rect)

ax2.callbacks.connect('xlim_changed', md.ax_update)
ax2.callbacks.connect('ylim_changed', md.ax_update)
ax2.set_title("Zoom here")

플롯 표시

show() 함수를 사용하여 플롯을 표시합니다.

plt.show()

요약

이 랩에서는 두 개의 동일한 패널과 UpdatingRect 및 MandelbrotDisplay 클래스를 사용하여 Matplotlib 에서 대화형 확대/축소 기능을 만드는 방법을 배웠습니다. 확대/축소 기능을 추가함으로써 플롯의 데이터를 더 잘 이해하고 분석할 수 있습니다.