소개
Matplotlib 는 Python 의 데이터 시각화 라이브러리입니다. 선 그래프, 산점도, 막대 그래프, 히스토그램 등 다양한 시각화를 생성하는 데 널리 사용됩니다. 이 튜토리얼에서는 Matplotlib 을 사용하여 계단식 히스토그램을 만드는 데 중점을 둡니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
필요한 라이브러리 및 모듈 가져오기
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import StepPatch
데이터 준비
np.random.seed(0)
h, edges = np.histogram(np.random.normal(5, 3, 5000),
bins=np.linspace(0, 10, 20))
간단한 계단형 히스토그램 생성
plt.stairs(h, edges, label='Simple histogram')
plt.legend()
plt.show()
계단형 히스토그램의 기준선 수정
plt.stairs(h, edges + 5, baseline=50, label='Modified baseline')
plt.legend()
plt.show()
엣지 (edges) 없이 계단형 히스토그램 생성
plt.stairs(h, edges + 10, baseline=None, label='No edges')
plt.legend()
plt.show()
채워진 히스토그램 생성
plt.stairs(np.arange(1, 6, 1), fill=True,
label='Filled histogram\nw/ automatic edges')
plt.legend()
plt.show()
해칭 (hatched) 된 히스토그램 생성
plt.stairs(np.arange(1, 6, 1)*0.3, np.arange(2, 8, 1),
orientation='horizontal', hatch='//',
label='Hatched histogram\nw/ horizontal orientation')
plt.legend()
plt.show()
StepPatch 아티스트 생성
patch = StepPatch(values=[1, 2, 3, 2, 1],
edges=range(1, 7),
label=('Patch derived underlying object\n'
'with default edge/facecolor behaviour'))
plt.gca().add_patch(patch)
plt.xlim(0, 7)
plt.ylim(-1, 5)
plt.legend()
plt.show()
스택 (stacked) 히스토그램 생성
A = [[0, 0, 0],
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]]
for i in range(len(A) - 1):
plt.stairs(A[i+1], baseline=A[i], fill=True)
plt.show()
.pyplot.step과 .pyplot.stairs 비교
bins = np.arange(14)
centers = bins[:-1] + np.diff(bins) / 2
y = np.sin(centers / 2)
plt.step(bins[:-1], y, where='post', label='step(where="post")')
plt.plot(bins[:-1], y, 'o--', color='grey', alpha=0.3)
plt.stairs(y - 1, bins, baseline=None, label='stairs()')
plt.plot(centers, y - 1, 'o--', color='grey', alpha=0.3)
plt.plot(np.repeat(bins, 2), np.hstack([y[0], np.repeat(y, 2), y[-1]]) - 1,
'o', color='red', alpha=0.2)
plt.legend()
plt.title('step() vs. stairs()')
plt.show()
요약
이 튜토리얼에서는 Matplotlib 을 사용하여 계단식 히스토그램을 생성하는 기본 사항을 다루었습니다. 간단한 step 히스토그램을 생성하고, 히스토그램의 baseline 을 수정하고, 채워진 (filled) 및 해치 (hatched) 히스토그램을 생성하고, 스택 (stacked) 히스토그램을 생성하는 방법을 배웠습니다. 또한 .pyplot.step과 .pyplot.stairs의 차이점을 비교했습니다.