Skip to content

Commit 6cf2b7c

Browse files
committed
FIX: align_x/ylabels
1 parent 756d1d4 commit 6cf2b7c

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

lib/matplotlib/figure.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1248,6 +1248,8 @@ def align_xlabels(self, axs=None):
12481248
if axs is None:
12491249
axs = self.axes
12501250
axs = np.ravel(axs)
1251+
axs = [ax for ax in axs if hasattr(ax, 'get_subplotspec')]
1252+
12511253
for ax in axs:
12521254
_log.debug(' Working on: %s', ax.get_xlabel())
12531255
rowspan = ax.get_subplotspec().rowspan
@@ -1308,6 +1310,8 @@ def align_ylabels(self, axs=None):
13081310
if axs is None:
13091311
axs = self.axes
13101312
axs = np.ravel(axs)
1313+
axs = [ax for ax in axs if hasattr(ax, 'get_subplotspec')]
1314+
13111315
for ax in axs:
13121316
_log.debug(' Working on: %s', ax.get_ylabel())
13131317
colspan = ax.get_subplotspec().colspan

lib/matplotlib/tests/test_figure.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,3 +1226,41 @@ def test_kwargs_pass():
12261226

12271227
assert fig.get_label() == 'whole Figure'
12281228
assert sub_fig.get_label() == 'sub figure'
1229+
1230+
1231+
def test_align_labels():
1232+
fig, axs = plt.subplots(2, 2)
1233+
for nn, ax in enumerate(axs.flat):
1234+
ax.set_xlabel('Boo')
1235+
ax.set_xlabel('Who')
1236+
ax.plot(np.arange(4)**nn, np.arange(4)**nn)
1237+
fig.align_ylabels()
1238+
fig.align_xlabels()
1239+
fig.draw_without_rendering()
1240+
xn = np.zeros(4)
1241+
yn = np.zeros(4)
1242+
for nn, ax in enumerate(axs.flat):
1243+
yn[nn] = ax.xaxis.label.get_position()[1]
1244+
xn[nn] = ax.yaxis.label.get_position()[0]
1245+
np.testing.assert_allclose(xn[:2], xn[2:])
1246+
np.testing.assert_allclose(yn[::2], yn[1::2])
1247+
1248+
fig, axs = plt.subplots(2, 2, constrained_layout=True)
1249+
for nn, ax in enumerate(axs.flat):
1250+
ax.set_xlabel('Boo')
1251+
ax.set_xlabel('Who')
1252+
pc = ax.pcolormesh(np.random.randn(10, 10))
1253+
fig.colorbar(pc, ax=ax)
1254+
fig.align_ylabels()
1255+
fig.align_xlabels()
1256+
fig.draw_without_rendering()
1257+
xn = np.zeros(4)
1258+
yn = np.zeros(4)
1259+
for nn, ax in enumerate(axs.flat):
1260+
yn[nn] = ax.xaxis.label.get_position()[1]
1261+
xn[nn] = ax.yaxis.label.get_position()[0]
1262+
np.testing.assert_allclose(xn[:2], xn[2:])
1263+
np.testing.assert_allclose(yn[::2], yn[1::2])
1264+
1265+
1266+

0 commit comments

Comments
 (0)