在matplotlib中为subplot添加标签

Gea*_*ric 5 python matplotlib

是否有自动方式将纯标签添加到子图中?具体来说,我用过

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
Run Code Online (Sandbox Code Playgroud)

我想在子图中的右上角添加'A'和'B'来区分它们,现在我正在使用虚拟方式

ax1.annotate('A', xy=(2, 1), xytext=(1, 22))
ax2.annotate('B', xy=(2, 1), xytext=(1, 22))
Run Code Online (Sandbox Code Playgroud)

我试过用

ax1.legend()
Run Code Online (Sandbox Code Playgroud)

这也给了我在字母之前的线条或点的"小图像",我不需要那个图像.

小智 8

您可以跳过编写辅助函数而只需调用:

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.annotate("A", xy=(0.9, 0.9), xycoords="axes fraction")
ax2.annotate("B", xy=(0.9, 0.9), xycoords="axes fraction")
Run Code Online (Sandbox Code Playgroud)


Hoo*_*ked 6

您可以使用annotate,但是您需要设置正确的限制,以便它们位于"右上角".如果在完成所有绘图后调用annotate命令,这应该可以工作,因为它从轴本身拉出限制.

import pylab as plt

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

def get_axis_limits(ax, scale=.9):
    return ax.get_xlim()[1]*scale, ax.get_ylim()[1]*scale

ax1.annotate('A', xy=get_axis_limits(ax1))
ax2.annotate('B', xy=get_axis_limits(ax2))
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

同样值得研究将文字放在图上的其他方法.