Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f06543e

Browse files
authored
Merge pull request #21762 from jklymak/fix-align-xylabels
FIX: align_x/ylabels
2 parents 3773128 + 5eb64f5 commit f06543e

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-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: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,41 @@ def test_align_labels():
6363
fig.align_labels()
6464

6565

66+
def test_align_labels_stray_axes():
67+
fig, axs = plt.subplots(2, 2)
68+
for nn, ax in enumerate(axs.flat):
69+
ax.set_xlabel('Boo')
70+
ax.set_xlabel('Who')
71+
ax.plot(np.arange(4)**nn, np.arange(4)**nn)
72+
fig.align_ylabels()
73+
fig.align_xlabels()
74+
fig.draw_without_rendering()
75+
xn = np.zeros(4)
76+
yn = np.zeros(4)
77+
for nn, ax in enumerate(axs.flat):
78+
yn[nn] = ax.xaxis.label.get_position()[1]
79+
xn[nn] = ax.yaxis.label.get_position()[0]
80+
np.testing.assert_allclose(xn[:2], xn[2:])
81+
np.testing.assert_allclose(yn[::2], yn[1::2])
82+
83+
fig, axs = plt.subplots(2, 2, constrained_layout=True)
84+
for nn, ax in enumerate(axs.flat):
85+
ax.set_xlabel('Boo')
86+
ax.set_xlabel('Who')
87+
pc = ax.pcolormesh(np.random.randn(10, 10))
88+
fig.colorbar(pc, ax=ax)
89+
fig.align_ylabels()
90+
fig.align_xlabels()
91+
fig.draw_without_rendering()
92+
xn = np.zeros(4)
93+
yn = np.zeros(4)
94+
for nn, ax in enumerate(axs.flat):
95+
yn[nn] = ax.xaxis.label.get_position()[1]
96+
xn[nn] = ax.yaxis.label.get_position()[0]
97+
np.testing.assert_allclose(xn[:2], xn[2:])
98+
np.testing.assert_allclose(yn[::2], yn[1::2])
99+
100+
66101
def test_figure_label():
67102
# pyplot figure creation, selection, and closing with label/number/instance
68103
plt.close('all')

0 commit comments

Comments
 (0)