这是我编写的用于自动对齐标签的函数,但它似乎不适用于脚本,只能交互。
def align_labels(axes_list,axis='y',align=None):
if align is None:
align = 'l' if axis == 'y' else 'b'
yx,xy = [],[]
for ax in axes_list:
yx.append(ax.yaxis.label.get_position()[0])
xy.append(ax.xaxis.label.get_position()[1])
if axis == 'x':
if align in ('t','top'):
lim = max(xy)
elif align in ('b','bottom'):
lim = min(xy)
else:
if align in ('l','left'):
lim = min(yx)
elif align in ('r','right'):
lim = max(yx)
if align in ('t','b','top','bottom'):
for ax in axes_list:
t = ax.xaxis.label.get_transform()
x,y = ax.xaxis.label.get_position()
ax.xaxis.set_label_coords(x,lim,t)
else:
for ax in axes_list:
t = ax.yaxis.label.get_transform()
x,y = ax.yaxis.label.get_position()
ax.yaxis.set_label_coords(lim,y,t)
还有一个例子:
fig,ax = subplots(2,2)
ax00,ax01 = ax[0]
ax10,ax11 = ax[1]
ax00.set_ylim(1000,5000)
ax00.set_ylabel('top')
ax10.set_ylabel('bottom')
ax10.set_xlabel('left')
ax11.set_xlabel('right')
ax11.xaxis.axis_date()
fig.autofmt_xdate()
#we have to call draw() so that matplotlib will figure out the automatic positions
fig.canvas.draw()
align_labels(ax[:,0],'y')
align_labels(ax[1],'x')