我编写了一个函数来自动执行此操作,其中将标签作为图例引入:
import numpy
import matplotlib.pyplot as plt
def setlabel(ax, label, loc=2, borderpad=0.6, **kwargs):
legend = ax.get_legend()
if legend:
ax.add_artist(legend)
line, = ax.plot(numpy.NaN,numpy.NaN,color='none',label=label)
label_legend = ax.legend(handles=[line],loc=loc,handlelength=0,handleheight=0,handletextpad=0,borderaxespad=0,borderpad=borderpad,frameon=False,**kwargs)
label_legend.remove()
ax.add_artist(label_legend)
line.remove()
fig,ax = plt.subplots()
ax.plot([1,2],[1,2])
setlabel(ax, '(a)')
plt.show()
标签的位置可以用loc参数控制,到轴的距离可以用borderpad参数控制(负值将标签推到图形之外),其他选项可用于@987654326 @也可以使用,如fontsize。上面的脚本给出了这样的图: