From 623445641b3a9bbe92c01d8b454b812bdd9f6ccb Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 2 Jun 2024 10:47:35 -0400 Subject: [PATCH] Backport PR #28292: Resolve MaxNLocator IndexError when no large steps --- lib/matplotlib/tests/test_ticker.py | 8 ++++++++ lib/matplotlib/ticker.py | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index 36b83c95b3d3..ac68a5d90b14 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -130,6 +130,14 @@ def test_view_limits_round_numbers_with_offset(self): loc = mticker.MultipleLocator(base=3.147, offset=1.3) assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447)) + def test_view_limits_single_bin(self): + """ + Test that 'round_numbers' works properly with a single bin. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MaxNLocator(nbins=1) + assert_almost_equal(loc.view_limits(-2.3, 2.3), (-4, 4)) + def test_set_params(self): """ Create multiple locator with 0.7 base, and change it to something else. diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index f042372a7be9..2b00937f9e29 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -2137,7 +2137,10 @@ def _raw_ticks(self, vmin, vmax): large_steps = large_steps & (floored_vmaxs >= _vmax) # Find index of smallest large step - istep = np.nonzero(large_steps)[0][0] + if any(large_steps): + istep = np.nonzero(large_steps)[0][0] + else: + istep = len(steps) - 1 # Start at smallest of the steps greater than the raw step, and check # if it provides enough ticks. If not, work backwards through