Matplotlib Span Selector

Beginner

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

소개

이 랩에서는 Matplotlib Span Selector 를 사용하여 축에서 범위를 선택하고 선택한 범위의 상세 보기를 다른 축에 플롯하는 방법을 안내합니다.

VM 팁

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

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

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

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

먼저, 필요한 라이브러리인 numpymatplotlib를 가져와야 합니다.

import numpy as np
import matplotlib.pyplot as plt

샘플 데이터 생성

이제 numpy를 사용하여 플롯할 샘플 데이터를 생성합니다.

## 재현성을 위해 난수 상태 고정
np.random.seed(19680801)

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2 * np.pi * x) + 0.5 * np.random.randn(len(x))

Figure 및 Subplot 생성

이제 matplotlib를 사용하여 두 개의 subplot 이 있는 figure 를 생성합니다.

fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6))

첫 번째 Subplot 에 데이터 플롯

첫 번째 subplot 에 샘플 데이터를 플롯합니다.

ax1.plot(x, y)
ax1.set_ylim(-2, 2)
ax1.set_title('Press left mouse button and drag '
              'to select a region in the top graph')

콜백 함수 정의

Span Selector 를 사용하여 범위를 선택했을 때 호출될 콜백 함수를 정의합니다.

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x) - 1, indmax)

    region_x = x[indmin:indmax]
    region_y = y[indmin:indmax]

    if len(region_x) >= 2:
        line2.set_data(region_x, region_y)
        ax2.set_xlim(region_x[0], region_x[-1])
        ax2.set_ylim(region_y.min(), region_y.max())
        fig.canvas.draw_idle()

Span Selector 생성

matplotlib.widgets.SpanSelector를 사용하여 Span Selector 객체를 생성합니다.

span = SpanSelector(
    ax1,
    onselect,
    "horizontal",
    useblit=True,
    props=dict(alpha=0.5, facecolor="tab:blue"),
    interactive=True,
    drag_from_anywhere=True
)

두 번째 서브플롯에 데이터 플롯

선택된 범위의 상세 보기를 두 번째 서브플롯에 플롯합니다.

line2, = ax2.plot([], [])

플롯 표시

이제 matplotlib.pyplot.show()를 사용하여 플롯을 표시합니다.

plt.show()

요약

이 랩에서는 Matplotlib Span Selector 를 사용하여 축에서 범위를 선택하고 선택된 범위의 상세 보기를 다른 축에 플롯하는 방법을 배웠습니다. 또한 Span Selector 객체를 생성하고 선택된 범위를 처리하는 콜백 함수를 정의하는 방법도 배웠습니다.