소개
이 랩에서는 Matplotlib 에서 앵커 객체 (Anchored Objects) 를 사용하는 방법을 배우게 됩니다. 앵커 객체는 플롯에 보조 객체를 추가하는 데 사용됩니다. 이러한 객체는 주석 (annotations), 스케일 바 (scale bars), 그리고 범례 (legends) 를 플롯에 추가하는 데 사용될 수 있습니다.
VM 팁
VM 시작이 완료되면, 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 접근하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사는 자동화될 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
라이브러리 임포트
첫 번째 단계는 필요한 라이브러리를 임포트하는 것입니다. 이 랩에서는 Matplotlib 을 사용할 것입니다.
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox,
DrawingArea, TextArea, VPacker)
from matplotlib.patches import Circle, Ellipse
Figure 생성
다음 단계는 figure 를 생성하는 것입니다. 단일 서브플롯 (subplot) 이 있는 간단한 figure 를 생성할 것입니다.
fig, ax = plt.subplots()
ax.set_aspect(1)
앵커된 텍스트 추가
이 단계에서는 figure 의 왼쪽 상단 모서리에 앵커된 텍스트 상자를 추가합니다.
def draw_text(ax):
"""Draw a text-box anchored to the upper-left corner of the figure."""
box = AnchoredOffsetbox(child=TextArea("Figure 1a"),
loc="upper left", frameon=True)
box.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(box)
draw_text(ax)
앵커된 원 추가
이 단계에서는 앵커된 객체 (Anchored Objects) 를 사용하여 플롯에 두 개의 원을 추가합니다.
def draw_circles(ax):
"""Draw circles in axes coordinates."""
area = DrawingArea(width=40, height=20)
area.add_artist(Circle((10, 10), 10, fc="tab:blue"))
area.add_artist(Circle((30, 10), 5, fc="tab:red"))
box = AnchoredOffsetbox(
child=area, loc="upper right", pad=0, frameon=False)
ax.add_artist(box)
draw_circles(ax)
앵커된 타원 추가
이 단계에서는 앵커된 객체 (Anchored Objects) 를 사용하여 플롯에 타원을 추가합니다.
def draw_ellipse(ax):
"""Draw an ellipse of width=0.1, height=0.15 in data coordinates."""
aux_tr_box = AuxTransformBox(ax.transData)
aux_tr_box.add_artist(Ellipse((0, 0), width=0.1, height=0.15))
box = AnchoredOffsetbox(child=aux_tr_box, loc="lower left", frameon=True)
ax.add_artist(box)
draw_ellipse(ax)
크기 막대 추가
이 단계에서는 앵커된 객체 (Anchored Objects) 를 사용하여 플롯에 크기 막대를 추가합니다.
def draw_sizebar(ax):
"""
Draw a horizontal bar with length of 0.1 in data coordinates,
with a fixed label center-aligned underneath.
"""
size = 0.1
text = r"1$^{\prime}$"
sizebar = AuxTransformBox(ax.transData)
sizebar.add_artist(Line2D([0, size], [0, 0], color="black"))
text = TextArea(text)
packer = VPacker(
children=[sizebar, text], align="center", sep=5) ## separation in points.
ax.add_artist(AnchoredOffsetbox(
child=packer, loc="lower center", frameon=False,
pad=0.1, borderpad=0.5)) ## paddings relative to the legend fontsize.
draw_sizebar(ax)
플롯 표시
마지막 단계는 플롯을 표시하는 것입니다.
plt.show()
요약
이 랩에서는 Matplotlib 에서 앵커된 객체 (Anchored Objects) 를 사용하는 방법을 배웠습니다. 앵커된 객체를 사용하여 플롯에 텍스트, 원, 타원 및 크기 막대를 추가하는 방법을 배웠습니다. 앵커된 객체는 플롯에 주석과 범례를 추가하는 데 사용할 수 있는 강력한 도구입니다.