소개
이 튜토리얼에서는 Matplotlib 라이브러리의 pcolormesh 함수를 사용하여 2D 이미지 스타일 플롯을 생성하는 방법을 배웁니다. pcolormesh의 기본 사용법, 비 - 직선형 (non-rectilinear) pcolormesh, 중심 좌표, 그리고 노름 (norm) 을 사용하여 레벨을 만드는 방법을 다룰 것입니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접속하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
기본 pcolormesh
일반적으로 우리는 사변형의 가장자리와 사변형의 값을 정의하여 pcolormesh 를 지정합니다. 여기서 x와 y는 각각 해당 차원에서 Z 보다 하나의 요소가 더 많다는 점에 유의하십시오.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
Z = np.random.rand(6, 10)
x = np.arange(-0.5, 10, 1) ## len = 11
y = np.arange(4.5, 11, 1) ## len = 7
fig, ax = plt.subplots()
ax.pcolormesh(x, y, Z)
비 - 직선형 (Non-rectilinear) pcolormesh
X와 Y에 대한 행렬을 지정하여 비 - 직선형 사변형을 가질 수도 있습니다.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
Z = np.random.rand(6, 10)
x = np.arange(-0.5, 10, 1) ## len = 11
y = np.arange(4.5, 11, 1) ## len = 7
X, Y = np.meshgrid(x, y)
X = X + 0.2 * Y ## tilt the coordinates.
Y = Y + 0.3 * X
fig, ax = plt.subplots()
ax.pcolormesh(X, Y, Z)
중심 좌표 (Centered coordinates)
사용자는 종종 .axes.Axes.pcolormesh에 Z와 동일한 크기의 X와 Y를 전달하려는 경우가 있습니다. 이는 shading='auto'가 전달된 경우에도 허용됩니다 (기본값은 :rc:pcolor.shading에 의해 설정됨). Matplotlib 3.3 이전에는 shading='flat'이 Z의 마지막 열과 행을 삭제했지만, 이제는 오류를 발생시킵니다. 이것이 정말로 원하는 것이라면, Z의 마지막 행과 열을 수동으로 삭제하십시오.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
Z = np.random.rand(6, 10)
x = np.arange(10) ## len = 10
y = np.arange(6) ## len = 6
X, Y = np.meshgrid(x, y)
fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
axs[0].pcolormesh(X, Y, Z, vmin=np.min(Z), vmax=np.max(Z), shading='auto')
axs[0].set_title("shading='auto' = 'nearest'")
axs[1].pcolormesh(X, Y, Z[:-1, :-1], vmin=np.min(Z), vmax=np.max(Z),
shading='flat')
axs[1].set_title("shading='flat'")
정규화를 사용하여 레벨 만들기 (Making levels using norms)
.axes.Axes.pcolor, .axes.Axes.pcolormesh 및 .axes.Axes.imshow 유형의 플롯에서 contour/contourf의 levels 키워드 인자와 유사한 방식으로 "레벨"을 그리기 위해 정규화 (Normalization) 및 컬러맵 (Colormap) 인스턴스를 결합하는 방법을 보여줍니다.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
## make these smaller to increase the resolution
dx, dy = 0.05, 0.05
## generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(1, 5 + dy, dy),
slice(1, 5 + dx, dx)]
z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)
## x and y are bounds, so z should be the value *inside* those bounds.
## Therefore, remove the last value from the z array.
z = z[:-1, :-1]
levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max())
## pick the desired colormap, sensible levels, and define a normalization
## instance which takes data values and translates those into levels.
cmap = plt.colormaps['PiYG']
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
fig, (ax0, ax1) = plt.subplots(nrows=2)
im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm)
fig.colorbar(im, ax=ax0)
ax0.set_title('pcolormesh with levels')
## contours are *point* based plots, so convert our bound into point
## centers
cf = ax1.contourf(x[:-1, :-1] + dx/2.,
y[:-1, :-1] + dy/2., z, levels=levels,
cmap=cmap)
fig.colorbar(cf, ax=ax1)
ax1.set_title('contourf with levels')
## adjust spacing between subplots so `ax1` title and `ax0` tick labels
## don't overlap
fig.tight_layout()
plt.show()
요약 (Summary)
이 튜토리얼에서는 Matplotlib 라이브러리의 pcolormesh 함수를 사용하는 방법을 배웠습니다. pcolormesh의 기본 사용법, 비 - 직선형 pcolormesh, 중심 좌표 (centered coordinates), 그리고 정규화 (norms) 를 사용하여 레벨을 만드는 방법을 다루었습니다. 이러한 기술은 Matplotlib 에서 다양한 유형의 2D 이미지 스타일 플롯을 생성하는 데 사용될 수 있습니다.