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

27
在向科学期刊提交论文时,经常需要用A、B等方式列举图表的不同子图。

enter image description here

这听起来像是一个很常见的问题,我试图找到一种优雅的方式来使用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')

enter image description here

编辑:

使用新的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')

我知道一定有一种优雅的方式。非常感谢。 - fabee
标记为重复问题,我回答了这个问题。我承认存在利益冲突,但是我按照问题的优先级进行回答。如果您感到不满,请告诉我。 - tacaswell
没有问题,尽管去做吧。 - Rutger Kassies
特别喜欢 string.ascii_uppercase[n] 这个技巧! - La Cordillera

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接