Skip to content

IndexFormatter doesn't round to the nearest integer #16631

@Wlodarski

Description

@Wlodarski

Bug report

Bug summary

Because IndexFormatter.__call__ doesn't round to the nearest integer but truncates/round up to the next integer, x ticks labels are duplicated when user pans plot to left, displaying values below minimum.

Code for reproduction

import matplotlib.pyplot as plt
from matplotlib.ticker import IndexFormatter

x = [1, 2, 3, 4, 5]
y = [1, 3, 5, 6, 0]
x_labels = ['under', 'a', 'b', 'c', 'd', 'e', 'over']

fig, ax = plt.subplots()
print(x[1])
ax.xaxis.set_major_formatter(IndexFormatter(x_labels))
ax.plot(x, y, '-o')
plt.show()

Actual outcome

bug

class IndexFormatter(Formatter):

[...]

    def __call__(self, x, pos=None):
        """
        Return the format for tick value `x` at position pos.

        The position is ignored and the value is rounded to the nearest
        integer ******** NOT TRUE *********, which is used to look up the label.
        """
        i = int(x + 0.5)
        if i < 0 or i >= self.n:
            return ''
        else:
            return self.labels[i]

IndexFormatter returns self.labels[0] for x = -1 instead of an empty string

Expected outcome

int_round

Proposed solution to correct [IndexFormatter] (https://matplotlib.org/3.1.3/_modules/matplotlib/ticker.html#IndexFormatter)

def __call__(self, x, pos=None):
        """
        Return the format for tick value `x` at position pos.

        The position is ignored and the value is rounded to the nearest
        integer, which is used to look up the label.
        """
        i = int(round(x))
        if i < 0 or i >= self.n:
            return ''
        else:
            return self.labels[i]

Matplotlib version

  • Matplotlib version: 3.1.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions