Matplotlib 中的锚定对象

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,你将学习如何在 Matplotlib 中使用锚定对象(Anchored Objects)。锚定对象用于向绘图添加辅助对象。这些对象可用于向绘图添加注释、比例尺和图例。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”(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

创建一个图形

下一步是创建一个图形。我们将创建一个带有单个子图的简单图形。

fig, ax = plt.subplots()
ax.set_aspect(1)

添加锚定文本

在这一步中,我们将添加一个锚定在图形左上角的文本框。

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)

添加锚定圆

在这一步中,我们将使用锚定对象在绘图中添加两个圆。

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)

添加锚定椭圆

在这一步中,我们将使用锚定对象在绘图中添加一个椭圆。

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)

添加比例尺

在这一步中,我们将使用锚定对象在绘图中添加一个比例尺。

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 中使用锚定对象。你学习了如何使用锚定对象在绘图中添加文本、圆形、椭圆形和比例尺。锚定对象是一个强大的工具,可用于在绘图中添加注释和图例。