Skip to content

Commit 7182602

Browse files
committed
FIX: Autoposition title when yaxis has offset
Move any title above the y axis offset text it would overlap with the offset. If multiple titles are present, they are vertically aligned to the highest one.
1 parent ac2a145 commit 7182602

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Move Axes title to not overlap with y axis offset
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
Axes titles that would overlap with y axis offset texts are now moved up if
5+
autopositioning is in effect (i.e. if *y* in ``.Axes.set_title`` is *None*
6+
and :rc:`axes.titley` is also *None*).
7+

lib/matplotlib/axes/_base.py

+6
Original file line numberDiff line numberDiff line change
@@ -2990,6 +2990,12 @@ def _update_title_position(self, renderer):
29902990
if bb is None:
29912991
bb = ax.get_window_extent(renderer)
29922992
top = max(top, bb.ymax)
2993+
if title.get_text():
2994+
ax.yaxis.get_tightbbox(renderer) # update offsetText
2995+
if ax.yaxis.offsetText.get_text():
2996+
bb = ax.yaxis.offsetText.get_tightbbox(renderer)
2997+
if bb.intersection(title.get_tightbbox(renderer), bb):
2998+
top = bb.ymax
29932999
if top < 0:
29943000
# the top of Axes is not even on the figure, so don't try and
29953001
# automatically place it.

lib/matplotlib/tests/test_axes.py

+30
Original file line numberDiff line numberDiff line change
@@ -6121,6 +6121,36 @@ def test_title_xticks_top_both():
61216121
assert ax.title.get_position()[1] > 1.04
61226122

61236123

6124+
@pytest.mark.parametrize(
6125+
'left, center', [
6126+
('left', ''),
6127+
('', 'center'),
6128+
('left', 'center')
6129+
], ids=[
6130+
'left title moved',
6131+
'center title kept',
6132+
'both titles aligned'
6133+
]
6134+
)
6135+
def test_title_above_offset(left, center):
6136+
# Test that title moves if overlaps with yaxis offset text.
6137+
mpl.rcParams['axes.titley'] = None
6138+
fig, ax = plt.subplots()
6139+
ax.set_ylim(1e11)
6140+
ax.set_title(left, loc='left')
6141+
ax.set_title(center)
6142+
fig.draw_without_rendering()
6143+
if left and not center:
6144+
assert ax._left_title.get_position()[1] > 1.0
6145+
elif not left and center:
6146+
assert ax.title.get_position()[1] == 1.0
6147+
else:
6148+
yleft = ax._left_title.get_position()[1]
6149+
ycenter = ax.title.get_position()[1]
6150+
assert yleft > 1.0
6151+
assert ycenter == yleft
6152+
6153+
61246154
def test_title_no_move_off_page():
61256155
# If an axes is off the figure (ie. if it is cropped during a save)
61266156
# make sure that the automatic title repositioning does not get done.

0 commit comments

Comments
 (0)