使用 GridSpec 进行子图定制

Beginner

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

简介

在本教程中,我们将学习如何使用 GridSpec 生成子图,通过 _width_ratios__height_ratios_ 控制子图的相对大小,以及使用子图参数(_left__right__bottom__top__wspace__hspace_)控制子图周围和之间的间距。

虚拟机使用提示

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

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

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

导入库

我们首先导入必要的库,即 matplotlib.pyplotGridSpec

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

使用 GridSpec 生成子图

在这一步中,我们将使用 GridSpec 来生成子图。我们将创建一个 2 行 2 列的图形。我们还将指定 width_ratiosheight_ratios 来控制子图的相对大小。

fig = plt.figure()
gs = GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[4, 1])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])
ax3 = fig.add_subplot(gs[2])
ax4 = fig.add_subplot(gs[3])

控制子图周围和之间的间距

在这一步中,我们将使用 GridSpec 来控制子图周围和之间的间距。我们将创建一个包含 2 个网格布局(gridspec)的图形,每个网格布局有 3 行 3 列。我们将指定 leftrightbottomtopwspacehspace 参数来控制间距。

fig = plt.figure()
gs1 = GridSpec(3, 3, left=0.05, right=0.48, wspace=0.05)
ax1 = fig.add_subplot(gs1[:-1, :])
ax2 = fig.add_subplot(gs1[-1, :-1])
ax3 = fig.add_subplot(gs1[-1, -1])

gs2 = GridSpec(3, 3, left=0.55, right=0.98, hspace=0.05)
ax4 = fig.add_subplot(gs2[:, :-1])
ax5 = fig.add_subplot(gs2[:-1, -1])
ax6 = fig.add_subplot(gs2[-1, -1])

标注坐标轴

在这一步中,我们将用相应的子图编号标注坐标轴。

def annotate_axes(fig):
    for i, ax in enumerate(fig.axes):
        ax.text(0.5, 0.5, "ax%d" % (i+1), va="center", ha="center")
        ax.tick_params(labelbottom=False, labelleft=False)

annotate_axes(fig)

显示图表

在这一步中,我们将显示图表。

plt.show()

总结

在本教程中,我们学习了如何使用 GridSpec 来生成子图,并控制子图周围和之间的间距。我们还学习了如何用相应的子图编号标注坐标轴。这些技巧在创建复杂的图表和可视化时会很有用。