Matplotlib 을 사용한 대화형 삼각 측량 플롯 생성

Beginner

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

소개

이 랩에서는 Matplotlib 을 사용하여 삼각 측량 플롯을 만드는 과정을 안내합니다. Triangulation 객체를 생성하고, TriFinder 객체를 사용하며, 커서 아래의 삼각형을 강조 표시하는 상호 작용을 설정하는 방법을 배우게 됩니다.

VM 팁

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

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

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

Triangulation 객체 생성

먼저, Triangulation 객체를 생성해야 합니다. matplotlib.tri에서 Triangulation 클래스를 사용합니다. 이 예제에서는 임의의 데이터를 사용하여 Triangulation 객체를 생성합니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.tri import Triangulation

## Generate random data
x = np.random.rand(10)
y = np.random.rand(10)
triang = Triangulation(x, y)

TriFinder 객체 생성

커서 아래의 삼각형을 찾기 위해 TriFinder 객체를 생성해야 합니다. get_trifinder() 메서드를 사용하여 Triangulation 객체에서 기본 TriFinder 객체를 얻을 수 있습니다.

trifinder = triang.get_trifinder()

플롯 설정

이제 플롯을 설정할 수 있습니다. plt.subplots()를 사용하여 figure 와 axis 객체를 생성합니다. 그런 다음 ax.triplot()을 사용하여 triangulation 을 플롯합니다.

fig, ax = plt.subplots()
ax.triplot(triang)

커서 아래 삼각형 강조

마우스가 플롯 위로 이동할 때 커서 아래의 삼각형을 강조 표시하려고 합니다. 이를 위해 커서 아래의 삼각형의 꼭지점으로 업데이트될 Polygon 객체를 생성합니다. ax.add_patch()를 사용하여 플롯에 polygon 을 추가합니다.

from matplotlib.patches import Polygon

polygon = Polygon([[0, 0], [0, 0], [0, 0]], facecolor='y')
ax.add_patch(polygon)

또한 커서 아래의 삼각형의 꼭지점으로 polygon 의 꼭지점을 업데이트하는 update_polygon() 함수를 생성합니다.

def update_polygon(tri):
    if tri == -1:
        points = [0, 0, 0]
    else:
        points = triang.triangles[tri]
    xs = triang.x[points]
    ys = triang.y[points]
    polygon.set_xy(np.column_stack([xs, ys]))

상호 작용 설정

커서 아래의 삼각형을 업데이트하기 위해 상호 작용을 설정해야 합니다. motion_notify_event를 사용하여 마우스가 플롯 위로 이동할 때를 감지합니다. TriFinder 객체를 사용하여 커서 아래의 삼각형을 가져오고, 삼각형의 꼭지점으로 polygon 을 업데이트하며, 삼각형의 인덱스로 플롯 제목을 업데이트하는 on_mouse_move() 함수를 생성합니다.

def on_mouse_move(event):
    if event.inaxes is None:
        tri = -1
    else:
        tri = trifinder(event.xdata, event.ydata)
    update_polygon(tri)
    ax.set_title(f'Triangle {tri}')
    event.canvas.draw()

fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)

플롯 표시

마지막으로 plt.show()를 사용하여 플롯을 표시할 수 있습니다.

plt.show()

요약

이 랩에서는 Matplotlib 을 사용하여 삼각 측량 플롯을 만드는 방법을 배웠습니다. TriangulationTriFinder 클래스를 사용하여 삼각 측량을 생성하고 커서 아래의 삼각형을 찾았습니다. 또한 커서 아래의 삼각형을 강조 표시하기 위해 상호 작용을 설정했습니다.