备注
前往结尾 下载完整示例代码。
子图标签#
子图的标签相对简单,并且有所不同,因此 Matplotlib 没有通用的方法来实现这一点。
我们展示了两种方法,用于将文本定位在距 Axes 角一定物理偏移(以字体大小单位或点为单位)的位置:一种使用 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))

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')

如果我们希望它与标题对齐,可以将其纳入标题中,或者使用 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()

参考文献
本示例展示了以下函数、方法、类和模块的使用: