소개
이 랩에서는 Matplotlib 에서 AnnotationBbox 를 사용하여 텍스트, 도형 및 이미지를 사용하여 그림에 주석을 다는 방법을 배웁니다. AnnotationBbox 는 Axes.annotate 보다 더 세밀한 제어 방법입니다. TextArea, DrawingArea 및 OffsetImage 의 세 가지 다른 OffsetBox 를 살펴보겠습니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 작업의 유효성 검사는 자동화할 수 없습니다.
학습 중에 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 즉시 해결해 드리겠습니다.
점 플로팅
시작하기 위해 나중에 주석을 달 두 점을 플로팅해 보겠습니다.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
## Define a 1st position to annotate (display it with a marker)
xy1 = (0.5, 0.7)
ax.plot(xy1[0], xy1[1], ".r")
## Define a 2nd position to annotate (don't display with a marker this time)
xy2 = [0.3, 0.55]
## Fix the display limits to see everything
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
TextArea 로 주석 달기
이제 TextArea 를 사용하여 첫 번째 점에 주석을 달아 보겠습니다.
from matplotlib.offsetbox import AnnotationBbox, TextArea
## Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1")
ab = AnnotationBbox(offsetbox, xy1,
xybox=(-20, 40),
xycoords='data',
boxcoords="offset points",
arrowprops=dict(arrowstyle="->"),
bboxprops=dict(boxstyle="sawtooth"))
ax.add_artist(ab)
plt.show()
DrawingArea 로 주석 달기
다음으로, DrawingArea 를 사용하여 두 번째 점에 원 패치를 사용하여 주석을 달아 보겠습니다.
from matplotlib.offsetbox import DrawingArea
from matplotlib.patches import Circle
## Annotate the 2nd position with a circle patch
da = DrawingArea(20, 20, 0, 0)
p = Circle((10, 10), 10)
da.add_artist(p)
ab = AnnotationBbox(da, xy2,
xybox=(1., xy2[1]),
xycoords='data',
boxcoords=("axes fraction", "data"),
box_alignment=(0.2, 0.5),
arrowprops=dict(arrowstyle="->"),
bboxprops=dict(alpha=0.5))
ax.add_artist(ab)
plt.show()
OffsetImage 로 주석 달기
마지막으로, Grace Hopper 의 이미지를 사용하여 OffsetImage 로 두 번째 점에 주석을 달아 보겠습니다.
from matplotlib.cbook import get_sample_data
from matplotlib.offsetbox import OffsetImage
## Annotate the 2nd position with an image (a generated array of pixels)
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr, zoom=2)
im.image.axes = ax
ab = AnnotationBbox(im, xy2,
xybox=(-50., 50.),
xycoords='data',
boxcoords="offset points",
pad=0.3,
arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)
## Annotate the 2nd position with another image (a Grace Hopper portrait)
with get_sample_data("grace_hopper.jpg") as file:
arr_img = plt.imread(file)
imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax
ab = AnnotationBbox(imagebox, xy2,
xybox=(120., -80.),
xycoords='data',
boxcoords="offset points",
pad=0.5,
arrowprops=dict(
arrowstyle="->",
connectionstyle="angle,angleA=0,angleB=90,rad=3")
)
ax.add_artist(ab)
plt.show()
요약
이 랩에서는 Matplotlib 에서 AnnotationBbox 를 사용하여 텍스트, 도형 및 이미지를 사용하여 그림에 주석을 다는 방법을 배웠습니다. TextArea, DrawingArea 및 OffsetImage 의 세 가지 다른 OffsetBox 를 살펴보았습니다. AnnotationBbox 를 사용함으로써 Axes.annotate 를 사용하는 것보다 주석에 대해 더 세밀한 제어를 할 수 있습니다.