Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 54e673c

Browse files
BUG: Fix IndexLocator.tick_values returning values greater than vmax
Fix IndexLocator.tick_values() to not return tick values that exceed vmax. Previously, when using IndexLocator with certain offset values, the generated ticks could exceed the specified vmax, causing issues like colorbar.get_ticks() returning incorrect values for discrete colormaps with NoNorm normalization. The fix adds a filter to remove any tick values greater than vmax after generating the initial tick positions. Fixes #31086
1 parent 2b8103b commit 54e673c

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

lib/matplotlib/tests/test_ticker.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,29 @@ def test_set_params(self):
604604
assert index._base == 7
605605
assert index.offset == 7
606606

607+
def test_tick_values_not_exceeding_vmax(self):
608+
"""
609+
Test that tick_values does not return values greater than vmax.
610+
Regression test for issue #31086.
611+
"""
612+
# Test case where offset=0 could cause vmax to be included incorrectly
613+
index = mticker.IndexLocator(base=1, offset=0)
614+
ticks = index.tick_values(0, 4)
615+
assert all(t <= 4 for t in ticks)
616+
np.testing.assert_array_equal(ticks, [0, 1, 2, 3, 4])
617+
618+
# Test case with fractional offset
619+
index = mticker.IndexLocator(base=1, offset=0.5)
620+
ticks = index.tick_values(0, 4)
621+
assert all(t <= 4 for t in ticks)
622+
np.testing.assert_array_equal(ticks, [0.5, 1.5, 2.5, 3.5])
623+
624+
# Test case with base > 1
625+
index = mticker.IndexLocator(base=2, offset=0)
626+
ticks = index.tick_values(0, 5)
627+
assert all(t <= 5 for t in ticks)
628+
np.testing.assert_array_equal(ticks, [0, 2, 4])
629+
607630

608631
class TestSymmetricalLogLocator:
609632
def test_set_params(self):

lib/matplotlib/ticker.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1767,8 +1767,10 @@ def __call__(self):
17671767
return self.tick_values(dmin, dmax)
17681768

17691769
def tick_values(self, vmin, vmax):
1770-
return self.raise_if_exceeds(
1771-
np.arange(vmin + self.offset, vmax + 1, self._base))
1770+
ticks = np.arange(vmin + self.offset, vmax + 1, self._base)
1771+
# Filter out ticks that exceed vmax to avoid off-by-one errors
1772+
ticks = ticks[ticks <= vmax]
1773+
return self.raise_if_exceeds(ticks)
17721774

17731775

17741776
class FixedLocator(Locator):

0 commit comments

Comments
 (0)