Skip to content

Commit 2f8b805

Browse files
rcomermeeseeksmachine
authored andcommitted
Backport PR matplotlib#31885: Skip hidden y-axis offset text when positioning titles (fix matplotlib#31881)
1 parent bd075d9 commit 2f8b805

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

lib/matplotlib/axes/_base.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3256,7 +3256,12 @@ def _update_title_position(self, renderer):
32563256
if title.get_text():
32573257
for ax in axs:
32583258
ax.yaxis.get_tightbbox(renderer) # update offsetText
3259-
if ax.yaxis.offsetText.get_text():
3259+
# A hidden offset text (e.g. on the shared y axis of an
3260+
# inner subplot) is not drawn, so it must not move the
3261+
# title: its tight bbox is non-finite and would otherwise
3262+
# push the title to infinity.
3263+
if (ax.yaxis.offsetText.get_visible()
3264+
and ax.yaxis.offsetText.get_text()):
32603265
bb = ax.yaxis.offsetText.get_tightbbox(renderer)
32613266
if bb.intersection(title.get_tightbbox(renderer), bb):
32623267
top = bb.ymax

lib/matplotlib/tests/test_axes.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7965,6 +7965,22 @@ def test_title_above_offset(left, center):
79657965
assert ycenter == yleft
79667966

79677967

7968+
def test_title_above_hidden_offset():
7969+
# On an inner subplot with a shared y axis the offset text is hidden, but
7970+
# it still carries text. It must not be considered when positioning the
7971+
# title: its tight bbox is non-finite and used to push the title (and the
7972+
# subplot position computed by tight_layout) to NaN/inf. See #31881.
7973+
mpl.rcParams['axes.titley'] = None
7974+
fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)
7975+
for i, ax in enumerate(axs):
7976+
ax.set_title(f'Subplot {i}')
7977+
ax.plot(range(10), [1e53] * 10)
7978+
fig.draw_without_rendering() # used to raise ValueError (NaN -> int)
7979+
for ax in axs:
7980+
assert np.isfinite(ax.title.get_window_extent().ymin)
7981+
assert np.all(np.isfinite(ax.get_position().bounds))
7982+
7983+
79687984
def test_title_no_move_off_page():
79697985
# If an Axes is off the figure (ie. if it is cropped during a save)
79707986
# make sure that the automatic title repositioning does not get done.

0 commit comments

Comments
 (0)