简介
在本实验中,我们将学习如何在 Matplotlib 中使用 AnnotationBbox,通过文本、形状和图像为图形添加注释。与 Axes.annotate 相比,AnnotationBbox 是一种粒度更细的控制方法。我们将介绍三种不同的 OffsetBox:TextArea、DrawingArea 和 OffsetImage。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
绘制点
首先,让我们绘制两个稍后要添加注释的点。
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
## 定义第一个要注释的位置(用标记显示它)
xy1 = (0.5, 0.7)
ax.plot(xy1[0], xy1[1], ".r")
## 定义第二个要注释的位置(这次不显示标记)
xy2 = [0.3, 0.55]
## 固定显示范围以查看所有内容
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
使用 TextArea 进行注释
现在让我们使用 TextArea 为第一个点添加注释。
from matplotlib.offsetbox import AnnotationBbox, TextArea
## 使用文本框(“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
## 用一个圆形补丁为第二个位置添加注释
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
## 用一张图片(一个生成的像素数组)为第二个位置添加注释
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)
## 用另一张图片(一张格蕾丝·霍珀的肖像)为第二个位置添加注释
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,通过文本、形状和图像为图形添加注释。我们介绍了三种不同的 OffsetBox:TextArea、DrawingArea 和 OffsetImage。通过使用 AnnotationBbox,与使用 Axes.annotate 相比,我们对注释有了更精细的控制。