소개
이 랩에서는 Python 의 Matplotlib 라이브러리를 사용하여 파이 차트와 도넛 차트를 만들 것입니다. 범례와 주석을 사용하여 차트에 레이블을 지정하는 방법을 배우게 됩니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접속하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
필요한 라이브러리 가져오기 및 서브플롯이 있는 그림 생성
필요한 라이브러리를 가져오고 서브플롯이 있는 그림을 생성하는 것으로 시작합니다.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))
파이 차트 생성
이제 밀가루, 설탕, 버터, 베리 등 4 가지 재료가 있는 레시피에 대한 파이 차트를 만들 것입니다.
recipe = ["375 g flour",
"75 g sugar",
"250 g butter",
"300 g berries"]
data = [float(x.split()[0]) for x in recipe]
ingredients = [x.split()[-1] for x in recipe]
def func(pct, allvals):
absolute = int(np.round(pct/100.*np.sum(allvals)))
return f"{pct:.1f}%\n({absolute:d} g)"
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
textprops=dict(color="w"))
ax.legend(wedges, ingredients,
title="Ingredients",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=8, weight="bold")
ax.set_title("Matplotlib bakery: A pie")
plt.show()
도넛 차트 생성
이제 밀가루, 설탕, 계란, 버터, 우유, 효모 등 6 가지 재료가 있는 레시피에 대한 도넛 차트를 만들 것입니다.
recipe = ["225 g flour",
"90 g sugar",
"1 egg",
"60 g butter",
"100 ml milk",
"1/2 package of yeast"]
data = [225, 90, 50, 60, 100, 5]
wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
bbox=bbox_props, zorder=0, va="center")
for i, p in enumerate(wedges):
ang = (p.theta2 - p.theta1)/2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = f"angle,angleA=0,angleB={ang}"
kw["arrowprops"].update({"connectionstyle": connectionstyle})
ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
horizontalalignment=horizontalalignment, **kw)
ax.set_title("Matplotlib bakery: A donut")
plt.show()
결론
Matplotlib 을 사용하여 파이 차트와 도넛 차트를 만드는 방법, 그리고 범례 (legend) 와 주석 (annotation) 으로 레이블을 지정하는 방법을 배웠습니다.
요약
이 랩 (lab) 에서는 Python 의 Matplotlib 라이브러리를 사용하여 파이 차트와 도넛 차트를 만드는 방법을 배웠습니다. 또한 범례 (legend) 와 주석 (annotation) 으로 레이블을 지정하는 방법도 배웠습니다.