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

Skip to content

Commit dd8e4b5

Browse files
committed
BUG fixed by @anntzer: correct tick labels with subsampled FixedLocator
When explicitly setting the tick locations and then the corresponding tick labels, a FixedLocator is used for the locations. It has an nbins argument that can trigger subsampling. Previously, tick labels were made by FixedFormatter and based on position, not value, so subsampling caused a mismatch, yielding incorrect tick labels. This is changed to use FuncFormatter with a function to look up the label by value, ignoring the position.
1 parent 5455bab commit dd8e4b5

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

lib/matplotlib/axis.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1626,11 +1626,18 @@ def set_ticklabels(self, ticklabels, *, minor=False, **kwargs):
16261626
"""
16271627
ticklabels = [t.get_text() if hasattr(t, 'get_text') else t
16281628
for t in ticklabels]
1629+
locator = (self.get_minor_locator() if minor
1630+
else self.get_major_locator())
1631+
if isinstance(locator, mticker.FixedLocator):
1632+
formatter = mticker.FuncFormatter(
1633+
lambda x, pos: ticklabels[[*locator.locs].index(x)])
1634+
else:
1635+
formatter = mticker.FixedFormatter(ticklabels)
16291636
if minor:
1630-
self.set_minor_formatter(mticker.FixedFormatter(ticklabels))
1637+
self.set_minor_formatter(formatter)
16311638
ticks = self.get_minor_ticks()
16321639
else:
1633-
self.set_major_formatter(mticker.FixedFormatter(ticklabels))
1640+
self.set_major_formatter(formatter)
16341641
ticks = self.get_major_ticks()
16351642
ret = []
16361643
for tick_label, tick in zip(ticklabels, ticks):

lib/matplotlib/ticker.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,8 +381,10 @@ class FuncFormatter(Formatter):
381381
position ``pos``), and return a string containing the corresponding
382382
tick label.
383383
"""
384+
384385
def __init__(self, func):
385386
self.func = func
387+
self.offset_string = ""
386388

387389
def __call__(self, x, pos=None):
388390
"""
@@ -392,6 +394,12 @@ def __call__(self, x, pos=None):
392394
"""
393395
return self.func(x, pos)
394396

397+
def get_offset(self):
398+
return self.offset_string
399+
400+
def set_offset_string(self, ofs):
401+
self.offset_string = ofs
402+
395403

396404
class FormatStrFormatter(Formatter):
397405
"""

0 commit comments

Comments
 (0)