Skip to content

FIX: Autoposition title when yaxis has offset #22063

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 6, 2022
Merged
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: 7 additions & 0 deletions doc/api/next_api_changes/behavior/22063-SR.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Move Axes title to not overlap with y axis offset
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Previously, Axes titles could overlap the y-axis offset text, which is often
in the upper left corner of the axes. Now titles are moved above the offset
text if overlapping, and autopositioning is in effect (i.e. if *y* in
`.Axes.set_title` is *None* and :rc:`axes.titley` is also *None*).
6 changes: 6 additions & 0 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2990,6 +2990,12 @@ def _update_title_position(self, renderer):
if bb is None:
bb = ax.get_window_extent(renderer)
top = max(top, bb.ymax)
if title.get_text():
ax.yaxis.get_tightbbox(renderer) # update offsetText
if ax.yaxis.offsetText.get_text():
bb = ax.yaxis.offsetText.get_tightbbox(renderer)
if bb.intersection(title.get_tightbbox(renderer), bb):
top = bb.ymax
if top < 0:
# the top of Axes is not even on the figure, so don't try and
# automatically place it.
Expand Down
30 changes: 30 additions & 0 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6121,6 +6121,36 @@ def test_title_xticks_top_both():
assert ax.title.get_position()[1] > 1.04


@pytest.mark.parametrize(
'left, center', [
('left', ''),
('', 'center'),
('left', 'center')
], ids=[
'left title moved',
'center title kept',
'both titles aligned'
]
)
def test_title_above_offset(left, center):
# Test that title moves if overlaps with yaxis offset text.
mpl.rcParams['axes.titley'] = None
fig, ax = plt.subplots()
ax.set_ylim(1e11)
ax.set_title(left, loc='left')
ax.set_title(center)
fig.draw_without_rendering()
if left and not center:
assert ax._left_title.get_position()[1] > 1.0
elif not left and center:
assert ax.title.get_position()[1] == 1.0
else:
yleft = ax._left_title.get_position()[1]
ycenter = ax.title.get_position()[1]
assert yleft > 1.0
assert ycenter == yleft


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