标注子图#

标注子图相对简单,并且方法多样,因此 Matplotlib 没有一个通用的方法来做这件事。

我们展示了两种方法,用于将文本定位在距离坐标轴某个角落特定物理偏移量(以字体大小单位或点为单位)的位置:一种使用 annotate,另一种使用 ScaledTranslation

为方便起见,本示例使用 pyplot.subplot_mosaic 并将子图标签作为子图的键。但是,此方法也适用于 pyplot.subplots 或与您想要标注子图的标签不同的键。

import matplotlib.pyplot as plt

from matplotlib.transforms import ScaledTranslation
fig, axs = plt.subplot_mosaic([['a)', 'c)'], ['b)', 'c)'], ['d)', 'd)']],
                              layout='constrained')
for label, ax in axs.items():
    # Use Axes.annotate to put the label
    # - at the top left corner (axes fraction (0, 1)),
    # - offset half-a-fontsize right and half-a-fontsize down
    #   (offset fontsize (+0.5, -0.5)),
    # i.e. just inside the axes.
    ax.annotate(
        label,
        xy=(0, 1), xycoords='axes fraction',
        xytext=(+0.5, -0.5), textcoords='offset fontsize',
        fontsize='medium', verticalalignment='top', fontfamily='serif',
        bbox=dict(facecolor='0.7', edgecolor='none', pad=3.0))
label subplots
fig, axs = plt.subplot_mosaic([['a)', 'c)'], ['b)', 'c)'], ['d)', 'd)']],
                              layout='constrained')
for label, ax in axs.items():
    # Use ScaledTranslation to put the label
    # - at the top left corner (axes fraction (0, 1)),
    # - offset 20 pixels left and 7 pixels up (offset points (-20, +7)),
    # i.e. just outside the axes.
    ax.text(
        0.0, 1.0, label, transform=(
            ax.transAxes + ScaledTranslation(-20/72, +7/72, fig.dpi_scale_trans)),
        fontsize='medium', va='bottom', fontfamily='serif')
label subplots

如果想让它与标题对齐,可以将其整合到标题中,或者使用 loc 关键字参数。

fig, axs = plt.subplot_mosaic([['a)', 'c)'], ['b)', 'c)'], ['d)', 'd)']],
                              layout='constrained')
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()
a), Normal Title, c), Normal Title, b), Normal Title, d), Normal Title

脚本总运行时间: (0 分钟 3.407 秒)

由 Sphinx-Gallery 生成的画廊