使用 Matplotlib 为子图添加标签

Beginner

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

简介

Matplotlib 是 Python 中广泛使用的数据可视化库。它提供了各种工具来创建不同类型的图表,包括子图。在创建子图时,给每个图表添加标签通常有助于读者更轻松地理解所呈现的信息。在本实验中,我们将学习如何使用 Matplotlib 提供的不同方法给子图添加标签。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入库

第一步是导入所需的库。我们将使用 matplotlib.pyplotmatplotlib.transforms 来创建和变换子图。

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms

创建子图

接下来,我们使用 plt.subplot_mosaic 创建子图。我们将创建一个 3x2 的子图网格,并按如下方式为它们标注:

  • 左上角的子图将标注为“a)”
  • 左下角的子图将标注为“b)”
  • 右上角和右下角的子图将分别标注为“c)”和“d)”
fig, axs = plt.subplot_mosaic([['a)', 'c)'], ['b)', 'c)'], ['d)', 'd)']], layout='constrained')

在坐标轴内添加标签

给子图添加标签最简单的方法是将标签放在坐标轴内。我们可以通过使用 ax.text 方法来实现这一点。我们将遍历每个子图,并使用 ax.transAxes 在坐标轴内添加标签。

for label, ax in axs.items():
    ## label physical distance in and down:
    trans = mtransforms.ScaledTranslation(10/72, -5/72, fig.dpi_scale_trans)
    ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,
            fontsize='medium', verticalalignment='top', fontfamily='serif',
            bbox=dict(facecolor='0.7', edgecolor='none', pad=3.0))

在坐标轴外添加标签

我们可能希望标签在坐标轴外,但仍相互对齐。在这种情况下,我们使用稍有不同的变换。

for label, ax in axs.items():
    ## label physical distance to the left and up:
    trans = mtransforms.ScaledTranslation(-20/72, 7/72, fig.dpi_scale_trans)
    ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,
            fontsize='medium', va='bottom', fontfamily='serif')

带标题的标签

如果我们希望标签与标题对齐,可以将其合并到标题中,或者使用 loc 关键字参数。

for label, ax in axs.items():
    ax.set_title('Normal Title', fontstyle='italic')
    ax.set_title(label, fontfamily='serif', loc='left', fontsize='medium')

显示子图

最后,我们使用 plt.show() 来显示子图。

plt.show()

总结

在本实验中,我们学习了如何使用不同方法在 Matplotlib 中为子图添加标签。我们使用 ax.text 在坐标轴内添加标签,使用 ax.set_title 结合标题添加标签,以及使用 plt.subplot_mosaic 创建子图。我们还使用 matplotlib.transforms 来变换坐标轴以对齐标签。通过为子图添加标签,我们可以使图表更具信息性且更易于理解。