Matplotlib 를 이용한 채워진 등고선 플롯

Beginner

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

소개

이 튜토리얼에서는 Matplotlib 라이브러리의 contourf 메서드를 사용하여 채워진 등고선 플롯을 만드는 방법을 배웁니다. 자동 및 명시적 레벨로 채워진 등고선을 생성하는 방법, 그리고 colormap 및 extend 설정을 하는 방법을 다룰 것입니다.

VM 팁

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

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

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

라이브러리 임포트 및 데이터 생성

먼저, 필요한 라이브러리를 임포트하고 플롯할 데이터를 생성해야 합니다.

import matplotlib.pyplot as plt
import numpy as np

## Create data
origin = 'lower'
delta = 0.025
x = y = np.arange(-3.0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
Z = (Z1 - Z2) * 2

자동 레벨을 사용한 채워진 등고선 생성

다음으로, 자동 레벨을 사용하여 채워진 등고선 플롯을 생성합니다. cmap 매개변수를 plt.cm.bone으로 설정하여 colormap 을 지정하는 contourf 메서드를 사용합니다. 또한 contour 메서드를 사용하여 등고선 라인을 추가하고, 채워진 등고선에 사용된 등고선 레벨의 하위 집합을 전달합니다.

## Create filled contour with automatic levels
fig, ax = plt.subplots()
CS = ax.contourf(X, Y, Z, 10, cmap=plt.cm.bone, origin=origin)
CS2 = ax.contour(CS, levels=CS.levels[::2], colors='r', origin=origin)

## Add title, axis labels, and colorbar
ax.set_title('Filled Contour with Automatic Levels')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
cbar = fig.colorbar(CS)
cbar.ax.set_ylabel('Z Label')
cbar.add_lines(CS2)

## Show plot
plt.show()

명시적 레벨을 사용한 채워진 등고선 생성

이제 명시적 레벨을 사용하여 채워진 등고선 플롯을 생성합니다. contourf 메서드를 사용하고 levels 매개변수를 값 목록으로 설정하여 등고선 레벨을 지정합니다. 또한 colormap 을 색상 목록으로 설정하고 extend 매개변수를 'both'로 설정하여 레벨 범위를 벗어나는 값을 표시합니다.

## Create filled contour with explicit levels
fig, ax = plt.subplots()
levels = [-1.5, -1, -0.5, 0, 0.5, 1]
CS = ax.contourf(X, Y, Z, levels, colors=('r', 'g', 'b'),
                 origin=origin, extend='both')
CS2 = ax.contour(X, Y, Z, levels, colors=('k',),
                 linewidths=(3,), origin=origin)

## Add title, axis labels, and colorbar
ax.set_title('Filled Contour with Explicit Levels')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
cbar = fig.colorbar(CS)
cbar.ax.set_ylabel('Z Label')

## Show plot
plt.show()

Colormap 및 Extend 설정

마지막으로, colormap 및 extend 설정을 설정합니다. with_extremes 메서드를 사용하여 레벨 범위 아래와 위의 값에 대한 색상을 설정합니다. 또한 네 가지 가능한 extend 설정인 'neither', 'both', 'min', 및 'max'를 표시하기 위해 네 개의 서브플롯을 생성합니다.

## Set colormap and extend settings
extends = ["neither", "both", "min", "max"]
cmap = plt.colormaps["winter"].with_extremes(under="magenta", over="yellow")

## Create subplots with different extend settings
fig, axs = plt.subplots(2, 2, layout="constrained")
for ax, extend in zip(axs.flat, extends):
    cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin)
    fig.colorbar(cs, ax=ax, shrink=0.9)
    ax.set_title("extend = %s" % extend)
    ax.locator_params(nbins=4)

## Show plot
plt.show()

요약

이 튜토리얼에서는 Matplotlib 라이브러리의 contourf 메서드를 사용하여 채워진 등고선 플롯을 만드는 방법을 배웠습니다. 자동 및 명시적 레벨을 사용하여 채워진 등고선을 생성하는 방법과 colormap 및 extend 설정을 설정하는 방법을 다루었습니다. 이러한 기술을 통해 데이터를 위한 아름답고 유익한 등고선 플롯을 만들 수 있습니다.