Matplotlib 를 이용한 삼각 등고선 (Tricontour) 부드럽게 그리기

Beginner

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

소개

이 튜토리얼은 Matplotlib 을 사용하여 고해상도 삼각 등고선 플롯을 생성하는 방법을 보여줍니다. 삼각 등고선 (Tricontouring) 은 비정형 삼각 메쉬 (unstructured triangular mesh) 에서 데이터를 표현하는 데 사용되는 기술입니다. 데이터가 불규칙하게 간격이 떨어진 지점에서 수집되거나, 데이터가 본질적으로 삼각 형태를 띨 때 자주 사용됩니다. 이 튜토리얼에서는 임의의 점 집합을 생성하고, 해당 점에 대한 들로네 삼각 분할 (Delaunay triangulation) 을 수행하고, 메쉬의 일부 삼각형을 마스크 처리하고, 데이터를 정제 및 보간하고, 마지막으로 Matplotlib 의 tricontour 함수를 사용하여 정제된 데이터를 플롯하는 방법을 보여줍니다.

VM 팁

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

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

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

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

첫 번째 단계는 필요한 라이브러리를 가져오는 것입니다. 이 튜토리얼에서는 NumPy 와 Matplotlib 을 사용합니다.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.tri import TriAnalyzer, Triangulation, UniformTriRefiner

테스트 함수 정의

다음으로, 실험 결과를 나타내는 함수를 정의합니다. 이 함수는 테스트 데이터 포인트를 생성하는 데 사용됩니다.

def experiment_res(x, y):
    """An analytic function representing experiment results."""
    x = 2 * x
    r1 = np.sqrt((0.5 - x)**2 + (0.5 - y)**2)
    theta1 = np.arctan2(0.5 - x, 0.5 - y)
    r2 = np.sqrt((-x - 0.2)**2 + (-y - 0.2)**2)
    theta2 = np.arctan2(-x - 0.2, -y - 0.2)
    z = (4 * (np.exp((r1/10)**2) - 1) * 30 * np.cos(3 * theta1) +
         (np.exp((r2/10)**2) - 1) * 30 * np.cos(5 * theta2) +
         2 * (x**2 + y**2))
    return (np.max(z) - z) / (np.max(z) - np.min(z))

테스트 데이터 포인트 생성

-1 과 1 사이의 x 및 y 값을 갖는 일련의 임의 테스트 데이터 포인트를 생성합니다. 또한 2 단계에서 정의된 experiment_res 함수를 사용하여 해당 z 값 집합을 생성합니다.

## User parameters for data test points

## Number of test data points, tested from 3 to 5000 for subdiv=3
n_test = 200

## Random points
random_gen = np.random.RandomState(seed=19680801)
x_test = random_gen.uniform(-1., 1., size=n_test)
y_test = random_gen.uniform(-1., 1., size=n_test)
z_test = experiment_res(x_test, y_test)

Delaunay 삼각 측량 수행

matplotlib.tri 모듈의 Triangulation 함수를 사용하여 테스트 데이터 포인트에 대한 Delaunay 삼각 측량 (Delaunay triangulation) 을 수행합니다.

## meshing with Delaunay triangulation
tri = Triangulation(x_test, y_test)
ntri = tri.triangles.shape[0]

일부 삼각형 마스크 처리

무효화된 데이터를 시뮬레이션하기 위해 메쉬 (mesh) 의 일부 삼각형을 마스크 처리합니다. init_mask_frac 매개변수를 기반으로 삼각형의 하위 집합을 무작위로 선택합니다.

## Some invalid data are masked out
mask_init = np.zeros(ntri, dtype=bool)
masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac))
mask_init[masked_tri] = True
tri.set_mask(mask_init)

삼각 측량 개선

TriAnalyzer를 사용하여 삼각 측량의 경계에서 모양이 좋지 않은 (평평한) 삼각형을 제거하여 삼각 측량을 개선합니다. 그런 다음 set_mask를 사용하여 삼각 측량에 마스크를 적용합니다.

## masking badly shaped triangles at the border of the triangular mesh.
mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio)
tri.set_mask(mask)

데이터 정제 및 보간

UniformTriRefiner를 사용하여 데이터를 정제하고 보간합니다.

## refining the data
refiner = UniformTriRefiner(tri)
tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv)

데이터 플롯

Matplotlib 의 tricontour 함수를 사용하여 정제된 데이터를 플롯합니다.

## Graphical options for tricontouring
levels = np.arange(0., 1., 0.025)

fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.set_title("Filtering a Delaunay mesh\n"
             "(application to high-resolution tricontouring)")

## plot of the refined (computed) data contours:
ax.tricontour(tri_refi, z_test_refi, levels=levels, cmap='Blues',
              linewidths=[2.0, 0.5, 1.0, 0.5])

plt.show()

요약

이 튜토리얼에서는 Matplotlib 을 사용하여 고해상도 삼각 등고선 플롯을 생성하는 방법을 시연했습니다. 먼저 일련의 임의 테스트 데이터 포인트를 생성하고, 해당 포인트에 대한 Delaunay 삼각 측량을 수행하고, 메쉬의 일부 삼각형을 마스킹하고, 데이터를 정제 및 보간한 다음, Matplotlib 의 tricontour 함수를 사용하여 정제된 데이터를 플롯하는 것으로 시작했습니다.