Visitar URL original
IndexFormatter doesn't round to the nearest integer · Issue #16631 · matplotlib/matplotlib · GitHub
The Wayback Machine - https://web.archive.org/web/20230301121535/https://github.com/matplotlib/matplotlib/issues/16631
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IndexFormatter doesn't round to the nearest integer #16631

Open
Wlodarski opened this issue Mar 2, 2020 · 22 comments
Open

IndexFormatter doesn't round to the nearest integer #16631

Wlodarski opened this issue Mar 2, 2020 · 22 comments

Comments

@Wlodarski
Copy link

Wlodarski commented Mar 2, 2020 •

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
@jklymak
Copy link
Member

jklymak commented Mar 2, 2020

I think you are correct that this is a bug, and we should use round rather than int(i+0.5). Would you care to make a PR?

@tacaswell
Copy link
Member

The issue is that int always goes towards 0 (as it is truncation not rounding).

@ImportanceOfBeingErnest
Copy link
Member

IndexFormatter is deprecated in #16170. Before trying to fix anything here, maybe one can identify if it is worth keeping or not?

@Wlodarski
Copy link
Author

IndexFormatter could have literally been fixed in less than 5 minutes. It's a tiny, tiny, extremely evident correction : a int(x + 0.5) replaced by int(round(x)). Now you are discussing deprecating the entire formatter along some others, which implies:

  • No backward compatibility. Beginners like me who are using this easy to understand function will lose it because users familiar with all the intricacies of matplotlib, those who wrote the examples, prefer a more complex way of achieving the same effect.
    • According the precepts of semantic versioning, deprecation is major version change since every single user of this function will have to replace it with another one. You are now talking of v4.xx.yy, not v3.3.0
      • You will have to update the documentation and teach all users like me that use IndexFormatter how to replace it with another function.

I am amazed how cascading and tedious is your process. No wonder why there are more than 1200 issues pending resolution. At the end of who knows how many days, maybe even weeks if not months, of deliberations, I won't be able to use IndexFormatter anymore, a function I was modestly trying to help fix... so I could continue use it without that annoying, tiny, tiny little bug. I was extremely naive. I regret submitting this easy fix. I learned my lesson. Life is too short to wasting it caught up in this procedural wrangles.

@ImportanceOfBeingErnest
Copy link
Member

Welcome to reality. ;-)
On a more serious note, though: We really appreaciate you taking the time to file a bug report here and to fix the problem. It is however not unusual that what seems like an easy fix will unroll to a major problem (programmers often call it a "rabbit hole"). There are two main points here:

  • The fix that you proposed lets the test suite fail. The tests are there to keep matplotlib stable and make sure we won't break it with seemingly obvious changes such as this one here. Of course there is always the possibility that the tests themselves are wrong as well. So any help in finding out if that test is simply incorrect, would be appreciated.
  • Totally independent of this issue at hand, IndexFormatter was deprecated in Deprecate old and little used formatters. #16170 already a month ago, scheduled for version 3.3.0. Such deprecations are common also to do in minor versions (see point 7 of the semantic versioning guide you link to). Note that deprecation means that the feature stays in the API, but releases a warning of it being removed in the future. The reason for the deprecation of IndexFormatter was that none of the developpers did know of a common use case for this formatter. If, however, you do have a good usecase, it is helpful to us to learn about it, instead of reading a rant about it going away. The more convincing this usecase is, the more likely the decision to remove it would be taken back.

@anntzer
Copy link
Contributor

anntzer commented Mar 3, 2020

Some more points:

  • Matplotlib does not follow semver in a strict sense: we will remove deprecated APIs in minor releases. FWIW Python doesn't strictly follow semver either: there has been APIs removed in minor Python releases too.

  • I deprecated IndexFormatter in Deprecate old and little used formatters. #16170 because @efiring suggested it in Deprecate old and little used formatters. #16170 (comment) (pushing the blame to someone else :-)) but in fact looking at it again it is super brittle (so I don't feel too bad about the deprecation); for example it will "break" if the ticker decides to also put ticks at half-integers:

from matplotlib import 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()
ax.xaxis.set_major_formatter(IndexFormatter(x_labels))
ax.plot(x, y, '-o')

plt.show()

bad

The correct fix is to use FuncFormatter, for which you can literally arrange to use whatever logic you want; for example:

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

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()
ax.xaxis.set_major_formatter(FuncFormatter(
    lambda x, _: dict(zip(range(len(x_labels)), x_labels)).get(x, "")))
ax.plot(x, y, '-o')

plt.show()

good

@Wlodarski
Copy link
Author

If the inner workings of FuncFormatter are superior to those of IndexFormatter, why don't you update IndexFormatter(x_labels) to become synonymous with FuncFormatter(lambda x, _: dict(zip(range(len(x_labels)), x_labels)).get(x, "")) ?

This way you would conserve backward compatibility.

@Wlodarski
Copy link
Author

Wlodarski commented Mar 3, 2020 •

  • The fix that you proposed lets the test suite fail.

It fails because the test requires the bug to be present. It expects the label for index -1 to display the label for index 0 instead of being empty as it should be.

@jklymak
Copy link
Member

jklymak commented Mar 3, 2020

As you can see, everything we include (or keep) in the library comes at a maintenance cost. In this case the value of the formatter was deemed to not be worth the cost in maintaining it. However, as said above, if there is a good use case for it, we can reconsider.

I hope you will have patience with us. This library is used by many thousand people, so there are indeed procedures to follow. Part of getting a "simple fix" into the code base is proving it doesn't break anything.

@anntzer
Copy link
Contributor

anntzer commented Mar 3, 2020

Any code needs to be maintained, documented, tested, generates bug reports and questions from the user that need to be fielded, etc.; meanwhile, developer time is finite. Hence it makes sense to remove little-used functionality, especially when reasonably simple alternatives exist.
The fact that two basic bugs (yours and mine) in IndexFormatter had never been reported before in more than 10 years(!) (the implementation dates back to 2009), even though they should be readily triggered (I found "my" bug completely accidentally while trying to understand yours...), strongly suggests to me that IndexFormatter is very rarely used and therefore does not warrant being part of Matplotlib itself.

@ImportanceOfBeingErnest
Copy link
Member

It obviously doesn't make sense to use an IndexFormatter without setting the ticks somehow (that is true for FixedFormatter as well).
Probably IndexFormatter was only ever meant to be used in conjunction with an IndexLocator. An example could be

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import IndexLocator, IndexFormatter

n = 2**np.arange(0, 10)
y = np.linspace(3, 7, 10)

fig, ax = plt.subplots()
ax.plot(y, "o-.")

ax.xaxis.set_major_locator(IndexLocator(1,0))
ax.xaxis.set_major_formatter(IndexFormatter(n))

plt.show()

image

@anntzer
Copy link
Contributor

anntzer commented Mar 3, 2020

Well, then there should be some sanity checks (as we have implemented for FixedFormatter) to avoid nonsensical results.

@Wlodarski
Copy link
Author

strongly suggests to me that IndexFormatter is very rarely used

Not at all. You are not an omniscient mind reader. It can and more likely suggests that most users of IndexFormatter don't notice or aren't bothered by this bug. Or they don't bother going through the hassle of reporting this little bug. I didn't notice it for months until I updated a software to insert data points prior index 0, and at first, I blamed myself. It also demonstrates that even some of the simplest bugs don't get fixed after more than a decade. Whoever wrote the test tailored it to disguise the bug as the expected behaviour.

And, to be frank, if I had to write a convoluted, barely readable lambda function the first time I encountered matplotlib, I would have never used it. For most users, lambda x, _: dict(zip(range(len(x_labels)), x_labels)).get(x, "") is horrific compared to just x_label. It's not what I call a "reasonably simple alternative".

Try to put yourself in the shoes of a casual user. What you propose, from a casual user standpoint, it's no different than you, someone familiar with the intricacies of matplotlib, having to decipher (lambda __g: [[[[(ax.xaxis.set_major_formatter(FuncFormatter((lambda x, _: (lambda __l: [dict(zip(range(len(x_labels)), x_labels)).get(__l['x'], '') for __l['x'], __l['_'] in [(x, _)]][0])({})))), (ax.plot(x, y, '-o'), (plt.show(), None)[1])[1])[1] for (__g['fig'], __g['ax']) in [(plt.subplots())]][0] for __g['x_labels'] in [(['under', 'a', 'b', 'c', 'd', 'e', 'over'])]][0] for __g['y'] in [([1, 3, 5, 6, 0])]][0] for __g['x'] in [([1, 2, 3, 4, 5])]][0])(globals()) .

You are deprecating a feature nobody complained about for a decade to have more time servicing hard to understand and hard to maintain features. It's like deprecating the trouble free factorial() function because you don't remember the last time somebody filed a bug about it and replacing it with lambda a, b: b*a(a, b-1) if b > 0 else 1 because more people ask you disambugation questions and fill bug reports regularly.

I don't see the usefulness of a system that make simple fixes tedious and evolves toward increased complexity by killing the simple things that work trouble free.

@ImportanceOfBeingErnest
Copy link
Member

ImportanceOfBeingErnest commented Mar 3, 2020 •

It by now seems clear that the example code in the bug report is a misuse of that formatter, because no ticks are specified, and an index of -1 is not sensical. What is seen as a bug here would not occur with the correct usage. This tells us that the IndexFormatter is poorly documented. We now have two options:

  1. Reinstate the index formatter, document it properly, and best install a safety net for when it's being used in the wrong fashion.
  2. Keep it deprecated, because it is so easy to be used in the wrong way - hence preventing future users to fall into that trap. Then tell people to use a FixedLocator and FixedFormatter instead.

Point 2. is considerably less work than point 1. But if it turns out that the IndexLocator/Formatter pair is correctly used by lots of people, reinstatement would sure be the way to go.

A final note here: The system actually works fine; and we see it in action just here: A bug was filed, an apparent solution proposed, a test was hit, making people aware of a problem, more people joining in, finding the actual problem, which is a different one than the bug suggested, and now one can work towards a solution.

@anntzer
Copy link
Contributor

anntzer commented Mar 3, 2020

I would also very kindly suggest that resorting to hyperbole and questioning the intent of the developers is not the best way to encourage us to take your input into consideration. In case this needs to be clarified, we are nearly all unpaid volunteers and have contributed thousands of hours of our free time to this project, which is available to you for free.

@tacaswell
Copy link
Member

Can everyone please take a breath. We all have the same goal (make Matplotlib the best it can be for our users).


It looks like the tests were added in #15962 as an exercise in increasing the test coverage and codified the existing behavior (rather than representing the intention of the original author). These tests also identified that the proposed change affects how ever-other half integer is rounded (as int(1.5) == 1 and round(1.5) == 2 (which is to avoid the "directional" bias by always going to towards even numbers)) so the effects are wider than just this fix.

An alternative fix would be to discard any negative values and leave the rounding behavior as-is.

@efiring
Copy link
Member

efiring commented Mar 3, 2020

I recommend leaving the IndexFormatter deprecated and removing it as scheduled. @Wlodarski, what are some examples of real-world usage of the IndexFormatter's functionality? Would it make sense to add an example to the docs or elsewhere using FuncFormatter? There is no need for the lambda; a normal function definition can be used, with as many lines as are needed to make it easy to read and understand.

@Wlodarski
Copy link
Author

@ImportanceOfBeingErnest With the proposed solution, neither option 1 nor option 2 is needed. And surely, those are not the only 2 options, nor the only conceivable solution. @tacaswell just proposed an alternative fix, the first fix that actually makes sense to me.

@ImportanceOfBeingErnest If an index of -1 is not sensical then the actual test is also not sensical since it makes sure the label associated with an index of 0 is displayed as a substitute for an index of -1.

In summary: The system is beyond tedious. It allowed a bug to remain hidden for more than a decade and gives the false impression the developers can infer actual usage based on saliency of problems. Trouble free functionalities are mistaken for useless functionalities, while functionalities that frequently suck the attention of the developers are promoted to further monopolize their efforts. A simple evident solution, rejected by a test that requires the bug to be present, is about to be swept under the rug in favour of increased complexity imposed on the users and malpractices like deprecations within a minor version. Explaining away malpractices by pointing out others also are tempted to commit them is not a valid point. What should have taken no time to solve definitively years ago while maintaining backward compatibility evolves toward a situation driven by a sunk cost fallacy. Criticism of the system is perceived as criticism of the volunteer developers, surely overworked in view of the heaviness of the system. You can tell yourself whatever you want but the fact is that a simple fix like rounding a value instead of truncating it ―replacing a int(x + 0.5) by round(x)― has become for many of you an unthinkable option while it seems perfectly reasonable to ask users to rewrite their programs with lambda functions encapsulating zipped iterables while, on your side, envisioning rewriting all the related documentation.

@anntzer I am not blaming any of you. You are the primary victims of this bureaucratic mess. The way the system is set up, for historical reasons I assume, robs of agility and makes the loss of perspective almost ineluctable. The handling of this extremely simple bug is symptomatic of this involuntary loss of perspective. It's bound to happen, especially after you have contributed thousands of hours of our free time to this project. When the easy solutions seem inconceivable and the hard convoluted ones seem far easier to implement, the system is not working for you anymore: you are working for it.

@Wlodarski
Copy link
Author

Would it make sense to add an example to the docs ...

If you are going the deprecation route, a recipe how to refactor IndexFormatter with minimal changes to the user's software might be helpful. For instance,

Add to your code :

def indexformatter(x, pos=None):
    return FuncFormatter(lambda x, _: dict(zip(range(len(x_labels)), x_labels)).get(x, ""))

and rename all instances of the uppercase IndexFormatter for the lowercaseindexformatter.

@tacaswell
Copy link
Member

@Wlodarski I will take you at your word that you intended to criticize the system, however your text reads as very direct personal criticisms of our volunteers which is not acceptable behavior.

@anntzer
Copy link
Contributor

anntzer commented Mar 3, 2020 •

As noted by @efiring the lambda is not optimal for legibility, I simply crammed everything in one line as this was easier to type quickly but a more legible version would be e.g.

def fmt_func(x, i):
	rounded = round(x)
    return labels[rounded] if 0 <= rounded < len(labels) else ""
fmt = FuncFormatter(fmt_func)

As for most API deprecations, an even simpler route for people not wanting to move to the new API would be to just copy-paste the old IndexFormatter implementation to their codebase (and possibly fix the round() bug at the same time).

In any case, I think this issue is in good hands now and will thus unsubscribe from it to avoid further miscommunication problems.

@tacaswell
Copy link
Member

I am inclined to close this with no-action because the IndexFormatter is slated to be deprecated. It has many issues (as both @ImportanceOfBeingErnest and @anntzer pointed out) and at least one bug (as reported here) when used in unintended ways.

If someone wants to open a PR that checks for being less than 0 before rounding (and correct 1 test case + document the behavior change) that would probably be merged for 3.3, but I do not think we need an open issue to track it.

I want to remind everyone again that we expect everyone to engage with each other in a professional manner and follow the PSF Code of Conduct (https://www.python.org/psf/conduct/) on github.


I think the OP's use case could be solved using the string categorical support:

y = [np.nan, 1, 3, 5, 6, 0, np.nan] 
x_labels = ['under', 'a', 'b', 'c', 'd', 'e', 'over'] 
fig, ax = plt.subplots() 
ax.set_xlim(-1, 7) 
ax.plot(x_labels, y, '-o')      

gh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

6 participants