Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3261,7 +3261,12 @@ def _update_title_position(self, renderer):
if title.get_text():
for ax in axs:
ax.yaxis.get_tightbbox(renderer) # update offsetText
if ax.yaxis.offsetText.get_text():
# A hidden offset text (e.g. on the shared y axis of an
# inner subplot) is not drawn, so it must not move the
# title: its tight bbox is non-finite and would otherwise
# push the title to infinity.
if (ax.yaxis.offsetText.get_visible()
and ax.yaxis.offsetText.get_text()):
bb = ax.yaxis.offsetText.get_tightbbox(renderer)
if bb.intersection(title.get_tightbbox(renderer), bb):
top = bb.ymax
Expand Down
16 changes: 16 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8009,6 +8009,22 @@ def test_title_above_offset(left, center):
assert ycenter == yleft


def test_title_above_hidden_offset():
# On an inner subplot with a shared y axis the offset text is hidden, but
# it still carries text. It must not be considered when positioning the
# title: its tight bbox is non-finite and used to push the title (and the
# subplot position computed by tight_layout) to NaN/inf. See #31881.
mpl.rcParams['axes.titley'] = None
fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)
for i, ax in enumerate(axs):
ax.set_title(f'Subplot {i}')
ax.plot(range(10), [1e53] * 10)
fig.draw_without_rendering() # used to raise ValueError (NaN -> int)
for ax in axs:
assert np.isfinite(ax.title.get_window_extent().ymin)
assert np.all(np.isfinite(ax.get_position().bounds))


def test_title_no_move_off_page():
# If an Axes is off the figure (ie. if it is cropped during a save)
# make sure that the automatic title repositioning does not get done.
Expand Down
Loading