From bc506ee31f0f7735104393b499fe414ae05d6106 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Thu, 21 Apr 2022 20:02:08 -0400 Subject: [PATCH] Backport PR #22871: Fix year offset not always being added --- lib/matplotlib/dates.py | 6 ++++-- lib/matplotlib/tests/test_dates.py | 4 ++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index 225f47907fb3..7c41e9ad5f3d 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -797,8 +797,10 @@ def format_ticks(self, values): # mostly 0: years, 1: months, 2: days, # 3: hours, 4: minutes, 5: seconds, 6: microseconds for level in range(5, -1, -1): - if len(np.unique(tickdate[:, level])) > 1: - if level < 2: + unique = np.unique(tickdate[:, level]) + if len(unique) > 1: + # if 1 is included in unique, the year is shown in ticks + if level < 2 and np.any(unique == 1): show_offset = False break elif level == 0: diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 49c38850a653..61a0aa34bb0b 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -621,6 +621,10 @@ def test_offset_changes(): ax.set_xlim(d1, d1 + datetime.timedelta(weeks=3)) fig.draw_without_rendering() assert formatter.get_offset() == '1997-Jan' + ax.set_xlim(d1 + datetime.timedelta(weeks=7), + d1 + datetime.timedelta(weeks=30)) + fig.draw_without_rendering() + assert formatter.get_offset() == '1997' ax.set_xlim(d1, d1 + datetime.timedelta(weeks=520)) fig.draw_without_rendering() assert formatter.get_offset() == ''