FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Error Handling of Non-Ints/Floats for postion of xticks · Issue #10147 · matplotlib/matplotlib · GitHub

Repository navigation

Error Handling of Non-Ints/Floats for postion of xticks #10147

Closed

Description

This appears to be the underlying cause of ticket #10130

I think this is an instance of inappropriate error handling in matplotlib.

I have been able to reproduce this running python 3.5 and matplotlib 2.1.1

The following code can reproduce the error and requires plt.close() to clean out the pipeline before more plotting can be done:

import matplotlib.pyplot as plt
data = [1,2,3,4,5]
ticks = ['any string']
plt.plot(data)
plt.xticks(ticks)
plt.show() 
AttributeError: 'NoneType' object has no attribute 'seq'

The error is set-up by assigning non int/floats to the first argument of xticks.

In:
https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/category.py

StrCategoryConverter.convert seems to exist for the handling of strings but it doesn't seem to be handling this particular scenario properly.

on line 44 if you add:

if axis.unit_data is None:
     axis.unit_data = UnitData([0])

It's a quick fix that makes it work but probably not the best solution. Its also of note that it is not just strings but data types other than int and float in the first argument of xticks will produce the same error.

While

plt.close()

Can be used to clear out the errors in jupyter notebook but I think that the error handling still can be improved.

An alternative fix could be to prevent xticks from assigning bad values like this in
https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/pyplot.py
on lines 1662-1667:

elif len(args)==1:
        if not any(isinstance(x, int) | isinstance(x, float) for x in args[0]):
            raise TypeError('First argument must be type int or float')
        locs = ax.set_xticks(args[0])
        labels = ax.get_xticklabels()
        
elif len(args)==2:
        if not any(isinstance(x, int) | isinstance(x, float) for x in args[0]):
            raise TypeError('First argument must be type int or float')
        locs = ax.set_xticks(args[0])
        labels = ax.set_xticklabels(args[1], **kwargs)   

Activity

  1. changed the title [-]Error Handling of None Ints/Floats for postion of xticks[/-] [+]Error Handling of Non-Ints/Floats for postion of xticks[/+] on Jan 3, 2018
  2. added this to the milestone on Jan 3, 2018
  3. jklymak commented on Jan 3, 2018

    Member

    Thanks a lot for the clear report. Without looking at it terribly deeply, I think this is a bug in unit handling, and the category unit handler should never have been called.

    Nonetheless, the where the error originates from is pretty clear in the error message:

    Traceback (most recent call last):
      File "tickissue.py", line 5, in <module>
        plt.xticks(ticks)
    

    I think your fixes above will just cover over the actual problem (and we never fix fundamental things in pyplot - its just a convenience wrapper).

  4. Rosuav commented on Jan 3, 2018

    The exception itself looks like an internal problem, though. It's confusing to see an AttributeError when the real problem is TypeError regarding the tick array. Perhaps the best solution is to trap the issue and raise something more meaningful?

  5. jklymak commented on Jan 3, 2018

    Member

    If you use #9776 which locks out other units converters once the converter has been set, then you get:

    pythonw testticks.py
    Traceback (most recent call last):
      File "testticks.py", line 5, in <module>
        plt.xticks(ticks)
      File "/Users/jklymak/matplotlib/lib/matplotlib/pyplot.py", line 1650, in xticks
        locs = ax.set_xticks(args[0])
      File "/Users/jklymak/matplotlib/lib/matplotlib/axes/_base.py", line 3068, in set_xticks
        ret = self.xaxis.set_ticks(ticks, minor=minor)
      File "/Users/jklymak/matplotlib/lib/matplotlib/axis.py", line 1660, in set_ticks
        ticks = self.convert_units(ticks)
      File "/Users/jklymak/matplotlib/lib/matplotlib/axis.py", line 1508, in convert_units
        ret = self.converter.convert(x, self.units, self)
      File "/Users/jklymak/matplotlib/lib/matplotlib/units.py", line 186, in convert
        return np.asarray(obj, dtype=np.float64)
      File "/Users/jklymak/anaconda3/envs/matplotlibdev/lib/python3.6/site-packages/numpy/core/numeric.py", line 531, in asarray
        return array(a, dtype, copy=False, order=order)
    ValueError: could not convert string to float: 'any string'
    

    Perhaps still suboptimal, in that it'd be better to check what unit converter would be registered and throw error if not the same, but at least much clearer than the error triggered above.

    My point is that the real error is that the categorical unit converter should never have been called, so fixing the categorical error handling for this case is papering over the real issue. Categorical support is still being hashed out, but has some side effects for the main code base.

    OTOH #9776 still has a different error for

    import matplotlib.pyplot as plt
    data = ['1','abc','4','5']
    ticks = ['abc']
    fig, ax = plt.subplots()
    ax.plot(data)
    ax.set_yticks(ticks)
    plt.show()

    in that it chooses '1' as the tick. But that is a bug in categorical.py in my opinion.

  6. story645 commented on Jan 3, 2018

    Member

    It's a quick fix that makes it work but probably not the best solution. Its also of note that it is not just strings but data types other than int and float in the first argument of xticks will produce the same error.

    Is that a problem? What you're saying is xtick gets mad if you pass in value in a unit other then the data, which sounds like what it should be doing? Maybe with a better error message?

    Also, this bug might be fixed in #9774 or #9783, but those are waiting on @tacaswell

    @jklymak #9776 is probably getting that error 'cause the default on Categoricals is to use FixedLocator.

  7. gurkpet commented on Jan 4, 2018

    Author

    Ya, I think a better error message would be appropriate. It took me awhile to figure out why I could no longer plot anything until I restarted the kernel. It will subsequently tell you the error is in whatever plotting function you are using rather than xticks. It could be that I am just to new to have seen what should have been obvious but it was quite frustrating at the time as I knew that some of my plots worked even though I was getting the same

    AttributeError: 'NoneType' object has no attribute 'seq'

    error long after first calling the bad xticks call. I think it should raise an error rather than allowing it to proceed to assign those values to anything that would continue to mess with plotting. But I am new and this is my first ever attempt at a contribution to a project so I am well aware I could be very wrong.

  8. jklymak commented on Jan 4, 2018

    Member

    I think its definitely a bug, and hence its labelled, so thanks a lot for the report!

    The problem is that plt.xticks(['boo']) should be a perfectly legal tick specification because Matplotlib now supports plotting calls like:

    fig, ax = plt.subplots()
    ax.plot(['boo', 'who', 'aardvark'], [1, 10, 3])
    ax.set_xticks(['boo', 'aardvark'])

    kind of works, though the order gets screwed up...

    Your problem was that:

    fig, ax = plt.subplots()
    ax.plot([1, 3, 10], [1, 10, 3])
    ax.set_xticks(['boo', 'aardvark'])

    is mixing "units", and the mysterious error was the result.

  9. github-actions commented on Apr 29, 2023

    This issue has been marked "inactive" because it has been 365 days since the last comment. If this issue is still present in recent Matplotlib releases, or the feature request is still wanted, please leave a comment and this label will be removed. If there are no updates in another 30 days, this issue will be automatically closed, but you are free to re-open or create a new issue if needed. We value issue reports, and this procedure is meant to help us resurface and prioritize issues that have not been addressed yet, not make them disappear. Thanks for your help!

  10. QuLogic commented on May 2, 2023

    Member

    This appears to be the same as #12990 which was fixed by #13005.

  11. modified the milestones: future releases, v3.1.0 on May 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions


      Back | FazBrowse Home | New Git URL