<p>如果不尝试导出矢量图形,或者设置了matplotlib后端以忽略无色轴,则廖文伟的回答是好的;否则隐藏的轴将显示在导出的图形中。</p>
<p>我的答案<code>suplabel</code>与使用<code>fig.text</code>函数的<code>fig.suptitle</code>类似。因此,没有斧头艺术家被创造和无色。
但是,如果您尝试多次调用它,您将得到相互添加的文本(正如<code>fig.suptitle</code>所做的那样)。廖文伟的回答不是,因为<code>fig.add_subplot(111)</code>如果已经创建了同一个Axes对象,那么它将返回该对象。</p>
<p>我的函数也可以在创建绘图后调用。</p>
<pre><code>def suplabel(axis,label,label_prop=None,
labelpad=5,
ha='center',va='center'):
''' Add super ylabel or xlabel to the figure
Similar to matplotlib.suptitle
axis - string: "x" or "y"
label - string
label_prop - keyword dictionary for Text
labelpad - padding from the axis (default: 5)
ha - horizontal alignment (default: "center")
va - vertical alignment (default: "center")
'''
fig = pylab.gcf()
xmin = []
ymin = []
for ax in fig.axes:
xmin.append(ax.get_position().xmin)
ymin.append(ax.get_position().ymin)
xmin,ymin = min(xmin),min(ymin)
dpi = fig.dpi
if axis.lower() == "y":
rotation=90.
x = xmin-float(labelpad)/dpi
y = 0.5
elif axis.lower() == 'x':
rotation = 0.
x = 0.5
y = ymin - float(labelpad)/dpi
else:
raise Exception("Unexpected axis: x or y")
if label_prop is None:
label_prop = dict()
pylab.text(x,y,label,rotation=rotation,
transform=fig.transFigure,
ha=ha,va=va,
**label_prop)
</code></pre>