From 6a2fcd12c076915ad7e1875adc3219e8650a9771 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Wed, 19 Aug 2020 13:30:10 +0200 Subject: [PATCH] Backport PR #18288: FIX: check if axes is off page before repositioning title --- lib/matplotlib/axes/_base.py | 8 ++++++-- lib/matplotlib/tests/test_axes.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 90e14580bfc2..336c678004ec 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -2614,7 +2614,6 @@ def _update_title_position(self, renderer): Update the title position based on the bounding box enclosing all the ticklabels and x-axis spine and xlabel... """ - if self._autotitlepos is not None and not self._autotitlepos: _log.debug('title position was updated manually, not adjusting') return @@ -2637,7 +2636,7 @@ def _update_title_position(self, renderer): else: ax.apply_aspect() axs = axs + [ax] - top = 0 + top = -np.Inf for ax in axs: if (ax.xaxis.get_ticks_position() in ['top', 'unknown'] or ax.xaxis.get_label_position() == 'top'): @@ -2646,6 +2645,11 @@ def _update_title_position(self, renderer): bb = ax.get_window_extent(renderer) if bb is not None: top = max(top, bb.ymax) + if top < 0: + # the top of axes is not even on the figure, so don't try and + # automatically place it. + _log.debug('top of axes not in the figure, so title not moved') + return if title.get_window_extent(renderer).ymin < top: _, y = self.transAxes.inverted().transform((0, top)) title.set_position((x, y)) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 6eedf20d50f5..8a7968aac52f 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -5430,6 +5430,19 @@ def test_title_xticks_top_both(): assert ax.title.get_position()[1] > 1.04 +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. + mpl.rcParams['axes.titley'] = None + fig = plt.figure() + ax = fig.add_axes([0.1, -0.5, 0.8, 0.2]) + ax.tick_params(axis="x", + bottom=True, top=True, labelbottom=True, labeltop=True) + tt = ax.set_title('Boo') + fig.canvas.draw() + assert tt.get_position()[1] == 1.0 + + def test_offset_label_color(): # Tests issue 6440 fig = plt.figure()