在图的子图中标注A、B、C

28 投票
1 回答
30581 浏览
提问于 2025-04-18 18:49

在向科学期刊提交论文时,通常需要给图中的不同子图标上字母,比如 A、B 等等。

在这里输入图片描述

这个问题听起来很常见,我想找一种优雅的方法,能用 matplotlib 自动完成这个任务,但我很惊讶地发现没有相关的信息。也许是我没有用对搜索词。理想情况下,我希望找到一种注释的方法,这样当图形被调整大小或者子图通过 fig.subplots_adjustfig.tight_layout 等方法移动时,字母能相对子图保持在原来的位置。

任何帮助或解决方案都非常感谢。

1 个回答

49

如果你想在子图上添加注释,那么使用 ax.text 来绘制注释对我来说是最方便的方法。

可以考虑这样做:

import numpy as np
import matplotlib.pyplot as plt
import string

fig, axs = plt.subplots(2,2,figsize=(8,8))
axs = axs.flat

for n, ax in enumerate(axs):
    
    ax.imshow(np.random.randn(10,10), interpolation='none')    
    ax.text(-0.1, 1.1, string.ascii_uppercase[n], transform=ax.transAxes, 
            size=20, weight='bold')

在这里输入图片描述

补充:

使用新的 plt.subplot_mosaic,上面的例子可以这样写。可能会显得稍微优雅一些。还可以考虑添加 constrained_layout=True

fig, axs = plt.subplot_mosaic("AB;CD", figsize=(10,10))

for n, (key, ax) in enumerate(axs.items()):

    ax.imshow(np.random.randn(10,10), interpolation='none')    
    ax.text(-0.1, 1.1, key, transform=ax.transAxes, 
            size=20, weight='bold')

撰写回答