Matplotlib 등고선 이미지

Beginner

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

소개

이 랩에서는 Python 의 Matplotlib 라이브러리를 사용하여 등고선 이미지 (contour image) 를 생성하는 방법을 배웁니다. 등고선 이미지는 3 차원 표면을 2 차원 플롯을 사용하여 나타내는 시각화 기술입니다. 등고선 이미지는 등고선 (contour lines) 으로 구성되며, 등고선은 표면에서 동일한 값을 갖는 점들을 연결하는 선이며, 채워진 등고선 (filled contours) 은 등고선 사이의 영역입니다.

VM 팁

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

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

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

라이브러리 임포트

이 단계에서는 등고선 이미지를 생성하는 데 필요한 라이브러리를 임포트합니다.

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import cm

데이터 정의

이 단계에서는 플롯할 데이터를 정의합니다. 데이터는 표면을 나타내는 값의 2 차원 배열입니다.

## Default delta is large because that makes it fast, and it illustrates
## the correct registration between image and contours.
delta = 0.5

extent = (-3, 4, -4, 3)

x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, 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

등고선 이미지 생성

이 단계에서는 Matplotlib 의 contourcontourf 함수를 사용하여 등고선 이미지를 생성합니다.

## Boost the upper limit to avoid truncation errors.
levels = np.arange(-2.0, 1.601, 0.4)

norm = cm.colors.Normalize(vmax=abs(Z).max(), vmin=-abs(Z).max())
cmap = cm.PRGn

fig, _axs = plt.subplots(nrows=2, ncols=2)
fig.subplots_adjust(hspace=0.3)
axs = _axs.flatten()

cset1 = axs[0].contourf(X, Y, Z, levels, norm=norm,
                        cmap=cmap.resampled(len(levels) - 1))
## It is not necessary, but for the colormap, we need only the
## number of levels minus 1.  To avoid discretization error, use
## either this number or a large number such as the default (256).

## If we want lines as well as filled regions, we need to call
## contour separately; don't try to change the edgecolor or edgewidth
## of the polygons in the collections returned by contourf.
## Use levels output from previous call to guarantee they are the same.

cset2 = axs[0].contour(X, Y, Z, cset1.levels, colors='k')

## We don't really need dashed contour lines to indicate negative
## regions, so let's turn them off.

for c in cset2.collections:
    c.set_linestyle('solid')

## It is easier here to make a separate call to contour than
## to set up an array of colors and linewidths.
## We are making a thick green line as a zero contour.
## Specify the zero level as a tuple with only 0 in it.

cset3 = axs[0].contour(X, Y, Z, (0,), colors='g', linewidths=2)
axs[0].set_title('Filled contours')
fig.colorbar(cset1, ax=axs[0])


axs[1].imshow(Z, extent=extent, cmap=cmap, norm=norm)
axs[1].contour(Z, levels, colors='k', origin='upper', extent=extent)
axs[1].set_title("Image, origin 'upper'")

axs[2].imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm)
axs[2].contour(Z, levels, colors='k', origin='lower', extent=extent)
axs[2].set_title("Image, origin 'lower'")

## We will use the interpolation "nearest" here to show the actual
## image pixels.
## Note that the contour lines don't extend to the edge of the box.
## This is intentional. The Z values are defined at the center of each
## image pixel (each color block on the following subplot), so the
## domain that is contoured does not extend beyond these pixel centers.
im = axs[3].imshow(Z, interpolation='nearest', extent=extent,
                   cmap=cmap, norm=norm)
axs[3].contour(Z, levels, colors='k', origin='image', extent=extent)
ylim = axs[3].get_ylim()
axs[3].set_ylim(ylim[::-1])
axs[3].set_title("Origin from rc, reversed y-axis")
fig.colorbar(im, ax=axs[3])

fig.tight_layout()
plt.show()

등고선 이미지 표시

이 단계에서는 등고선 이미지를 표시합니다.

fig.tight_layout()
plt.show()

요약

이 랩에서는 Python 의 Matplotlib 라이브러리를 사용하여 등고선 이미지를 생성하는 방법을 배웠습니다. 필요한 라이브러리를 가져오고, 플롯할 데이터를 정의하고, 등고선 이미지를 생성하고, 이미지를 표시하는 것으로 시작했습니다. 등고선 이미지는 2 차원 플롯을 사용하여 3 차원 표면을 나타내는 데 사용할 수 있는 유용한 시각화 기술입니다.