라쏘 선택기 데모 (Lasso Selector Demo)

Beginner

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

소개

이 랩에서는 Python Matplotlib 을 사용하여 라쏘 도구로 데이터 포인트를 대화식으로 선택하는 방법을 배웁니다. 산점도를 그리고 그래프의 점 주위에 라쏘 루프를 그려서 몇 개의 점을 선택합니다. 그리려면 그래프를 클릭하고, 누른 상태에서 선택하려는 점 주위로 드래그하면 됩니다.

VM 팁

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

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

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

라이브러리 임포트

numpy, Path, 그리고 LassoSelector를 포함한 필요한 라이브러리를 임포트합니다.

import numpy as np
from matplotlib.path import Path
from matplotlib.widgets import LassoSelector

선택기 클래스 생성

LassoSelector를 사용하여 Matplotlib 컬렉션에서 인덱스를 선택하는 SelectFromCollection 클래스를 생성합니다.

class SelectFromCollection:
    """
    `LassoSelector` 를 사용하여 matplotlib 컬렉션에서 인덱스를 선택합니다.

    선택된 인덱스는 `ind` 속성에 저장됩니다. 이 도구는 선택에 포함되지 않은 점을 흐리게 합니다 (즉, 알파 값을 줄입니다). 컬렉션의 알파 값이 1 미만인 경우, 이 도구는 알파 값을 영구적으로 변경합니다.

    이 도구는 *원점* (즉, `offsets`) 을 기반으로 컬렉션 객체를 선택합니다.

    매개변수
    ----------
    ax : `~matplotlib.axes.Axes`
        상호 작용할 축.
    collection : `matplotlib.collections.Collection` 서브클래스
        선택하려는 컬렉션.
    alpha_other : 0 <= float <= 1
        선택을 강조 표시하기 위해 이 도구는 선택된 모든 점의 알파 값을 1 로 설정하고 선택되지 않은 점의 알파 값을 *alpha_other*로 설정합니다.
    """

    def __init__(self, ax, collection, alpha_other=0.3):
        self.canvas = ax.figure.canvas
        self.collection = collection
        self.alpha_other = alpha_other

        self.xys = collection.get_offsets()
        self.Npts = len(self.xys)

        ## Ensure that we have separate colors for each object
        self.fc = collection.get_facecolors()
        if len(self.fc) == 0:
            raise ValueError('Collection must have a facecolor')
        elif len(self.fc) == 1:
            self.fc = np.tile(self.fc, (self.Npts, 1))

        self.lasso = LassoSelector(ax, onselect=self.onselect)
        self.ind = []

    def onselect(self, verts):
        path = Path(verts)
        self.ind = np.nonzero(path.contains_points(self.xys))[0]
        self.fc[:, -1] = self.alpha_other
        self.fc[self.ind, -1] = 1
        self.collection.set_facecolors(self.fc)
        self.canvas.draw_idle()

    def disconnect(self):
        self.lasso.disconnect_events()
        self.fc[:, -1] = 1
        self.collection.set_facecolors(self.fc)
        self.canvas.draw_idle()

산점도 생성

무작위로 생성된 데이터를 사용하여 산점도를 생성합니다.

np.random.seed(19680801)
data = np.random.rand(100, 2)

subplot_kw = dict(xlim=(0, 1), ylim=(0, 1), autoscale_on=False)
fig, ax = plt.subplots(subplot_kw=subplot_kw)
pts = ax.scatter(data[:, 0], data[:, 1], s=80)
selector = SelectFromCollection(ax, pts)

선택된 점 수락

Enter 키를 사용하여 선택된 점을 수락하고 콘솔에 출력합니다.

def accept(event):
    if event.key == "enter":
        print("Selected points:")
        print(selector.xys[selector.ind])
        selector.disconnect()
        ax.set_title("")
        fig.canvas.draw()

fig.canvas.mpl_connect("key_press_event", accept)
ax.set_title("Press enter to accept selected points.")

plt.show()

요약

이 랩에서는 Python Matplotlib 을 사용하여 라쏘 도구로 데이터 포인트를 대화식으로 선택하는 방법을 배웠습니다. 산점도를 생성하고, 그래프의 점 주위에 라쏘 루프를 그려 몇 개의 점을 선택한 다음, Enter 키를 사용하여 선택된 점을 수락했습니다.