Python Matplotlib 을 이용한 등고선 플롯 생성

Beginner

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

소개

이 랩은 Python Matplotlib 을 사용하여 등고선 플롯을 만드는 방법에 대한 단계별 튜토리얼입니다. 등고선 플롯은 3 차원 데이터를 2 차원으로 시각화하는 데 유용합니다. 이 튜토리얼에서는 간단한 등고선 플로팅, 등고선에 대한 이미지와 등고선에 대한 컬러바, 그리고 레이블이 지정된 등고선을 설명합니다.

VM 팁

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

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

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

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

등고선 플롯을 만들기 전에 필요한 라이브러리를 가져와야 합니다. 이 튜토리얼에서는 numpy 와 matplotlib 을 사용합니다.

import matplotlib.pyplot as plt
import numpy as np

데이터 생성

등고선 플롯을 만드는 데 사용할 데이터를 생성해야 합니다. 이 예제에서는 두 개의 2D 가우시안 함수를 생성합니다.

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, 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

레이블이 있는 간단한 등고선 플롯 생성

이제 데이터를 갖추었으므로 기본 색상을 사용하여 레이블이 있는 간단한 등고선 플롯을 만들 수 있습니다.

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
ax.clabel(CS, inline=True, fontsize=10)
ax.set_title('Simplest default with labels')

등고선 레이블 수동 배치

데이터 좌표에서 위치 목록을 제공하여 등고선 레이블을 수동으로 배치할 수도 있습니다.

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)
manual_locations = [
    (-1, -1.4), (-0.62, -0.7), (-2, 0.5), (1.7, 1.2), (2.0, 1.4), (2.4, 1.7)]
ax.clabel(CS, inline=True, fontsize=10, manual=manual_locations)
ax.set_title('labels at selected locations')

등고선 색상 설정

모든 등고선이 동일한 색상을 갖도록 하거나 음수 등고선을 점선 대신 실선으로 설정할 수 있습니다.

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6, colors='k')  ## Negative contours default to dashed.
ax.clabel(CS, fontsize=9, inline=True)
ax.set_title('Single color - negative contours dashed')
plt.rcParams['contour.negative_linestyle'] = 'solid'
fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6, colors='k')  ## Negative contours default to dashed.
ax.clabel(CS, fontsize=9, inline=True)
ax.set_title('Single color - negative contours solid')

등고선 색상 수동 지정

또한 등고선의 색상을 수동으로 지정할 수 있습니다.

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z, 6,
                linewidths=np.arange(.5, 4, .5),
                colors=('r', 'green', 'blue', (1, 1, 0), '#afeeee', '0.5'),
                )
ax.clabel(CS, fontsize=9, inline=True)
ax.set_title('Crazy lines')

Colormap 을 사용하여 등고선 색상 지정

Colormap 을 사용하여 등고선 색상을 지정할 수 있습니다.

fig, ax = plt.subplots()
im = ax.imshow(Z, interpolation='bilinear', origin='lower',
               cmap=cm.gray, extent=(-3, 3, -2, 2))
levels = np.arange(-1.2, 1.6, 0.2)
CS = ax.contour(Z, levels, origin='lower', cmap='flag', extend='both',
                linewidths=2, extent=(-3, 3, -2, 2))

## Thicken the zero contour.
CS.collections[6].set_linewidth(4)

ax.clabel(CS, levels[1::2],  ## label every second level
          inline=True, fmt='%1.1f', fontsize=14)

## make a colorbar for the contour lines
CB = fig.colorbar(CS, shrink=0.8)

ax.set_title('Lines with colorbar')

## We can still add a colorbar for the image, too.
CBI = fig.colorbar(im, orientation='horizontal', shrink=0.8)

## This makes the original colorbar look a bit out of place,
## so let's improve its position.

l, b, w, h = ax.get_position().bounds
ll, bb, ww, hh = CB.ax.get_position().bounds
CB.ax.set_position([ll, b + 0.1*h, ww, h*0.8])

요약

이 랩에서는 Python Matplotlib 을 사용하여 등고선 플롯을 만드는 방법을 배웠습니다. 레이블이 있는 간단한 등고선 플롯 생성, 등고선 레이블 수동 배치, 등고선 색상 설정, 등고선 색상 수동 지정, 그리고 colormap 을 사용하여 등고선 색상 지정에 대해 다루었습니다.