Skip to content

creating PathCollection proxy artist with %matplotlib inline raises ValueError: cannot convert float NaN to integer #10360

Closed

Description

@DizietAsahi

First, I'm not sure if this is a matplotlibor a jupyter bug, so I apologize if I'm posting at the wrong place.

I'm having some problems with some code that used to work in a previous version of maptlotlib+jupyter notebook.
I managed to trace the problem to creating an empty PathCollection to be used as a legend proxy artist, but the Exception is only raised when using the inline backend (%matplotlib inline). The code works fine using %matplotlib notebook or in ipython using the MacOSX backend

Bug report

Bug summary

Code for reproduction

%matplotlib inline
from matplotlib import pyplot as plt
_, ax = plt.subplots()
a = ax.scatter([], [], clip_on=False,
                 marker='s', s=20, facecolor='k', 
                 edgecolors='r', linewidths=5, 
                 zorder=100, label='label')
ax.legend(handles=[a])

plt.show()

Actual outcome

ValueError                                Traceback (most recent call last)
~/anaconda3/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

~/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    236 
    237     if 'png' in formats:
--> 238         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    239     if 'retina' in formats or 'png2x' in formats:
    240         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

~/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    120 
    121     bytes_io = BytesIO()
--> 122     fig.canvas.print_figure(bytes_io, **kw)
    123     data = bytes_io.getvalue()
    124     if fmt == 'svg':

~/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2265                 orientation=orientation,
   2266                 bbox_inches_restore=_bbox_inches_restore,
-> 2267                 **kwargs)
   2268         finally:
   2269             if bbox_inches and restore_bbox:

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    505 
    506     def print_png(self, filename_or_obj, *args, **kwargs):
--> 507         FigureCanvasAgg.draw(self)
    508         renderer = self.get_renderer()
    509         original_dpi = renderer.dpi

~/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    428             # if toolbar:
    429             #     toolbar.set_cursor(cursors.WAIT)
--> 430             self.figure.draw(self.renderer)
    431         finally:
    432             # if toolbar:

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py in draw(self, renderer)
   1297 
   1298             mimage._draw_list_compositing_images(
-> 1299                 renderer, self, artists, self.suppressComposite)
   1300 
   1301             renderer.close_group('figure')

~/anaconda3/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2435             renderer.stop_rasterizing()
   2436 
-> 2437         mimage._draw_list_compositing_images(renderer, self, artists)
   2438 
   2439         renderer.close_group('axes')

~/anaconda3/lib/python3.6/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

~/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     53                 renderer.start_filter()
     54 
---> 55             return draw(artist, renderer, *args, **kwargs)
     56         finally:
     57             if artist.get_agg_filter() is not None:

~/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1131         renderer.open_group(__name__)
   1132 
-> 1133         ticks_to_draw = self._update_ticks(renderer)
   1134         ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
   1135                                                                 renderer)

~/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
    972 
    973         interval = self.get_view_interval()
--> 974         tick_tups = list(self.iter_ticks())
    975         if self._smart_bounds and tick_tups:
    976             # handle inverted limits

~/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py in iter_ticks(self)
    915         Iterate through all of the major and minor ticks.
    916         """
--> 917         majorLocs = self.major.locator()
    918         majorTicks = self.get_major_ticks(len(majorLocs))
    919         self.major.formatter.set_locs(majorLocs)

~/anaconda3/lib/python3.6/site-packages/matplotlib/ticker.py in __call__(self)
   1951     def __call__(self):
   1952         vmin, vmax = self.axis.get_view_interval()
-> 1953         return self.tick_values(vmin, vmax)
   1954 
   1955     def tick_values(self, vmin, vmax):

~/anaconda3/lib/python3.6/site-packages/matplotlib/ticker.py in tick_values(self, vmin, vmax)
   1959         vmin, vmax = mtransforms.nonsingular(
   1960             vmin, vmax, expander=1e-13, tiny=1e-14)
-> 1961         locs = self._raw_ticks(vmin, vmax)
   1962 
   1963         prune = self._prune

~/anaconda3/lib/python3.6/site-packages/matplotlib/ticker.py in _raw_ticks(self, vmin, vmax)
   1901         if self._nbins == 'auto':
   1902             if self.axis is not None:
-> 1903                 nbins = np.clip(self.axis.get_tick_space(),
   1904                                 max(1, self._min_n_ticks - 1), 9)
   1905             else:

~/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py in get_tick_space(self)
   2060         size = tick.label1.get_size() * 3
   2061         if size > 0:
-> 2062             return int(np.floor(length / size))
   2063         else:
   2064             return 2**31 - 1

ValueError: cannot convert float NaN to integer

Expected outcome

The exact same code using %matplotlib notebook

%matplotlib notebook
from matplotlib import pyplot as plt
_, ax = plt.subplots()
a = ax.scatter([], [], clip_on=False,
                 marker='s', s=20, facecolor='k', 
                 edgecolors='r', linewidths=5, 
                 zorder=100, label='label')
ax.legend(handles=[a])

plt.show()

produces the expected output
download

The code using %matplotlib inline used to work before, but unfortunately, I don't know which version of matplotlib/jupyter I was using

Matplotlib version

  • Operating system: OSX
  • Matplotlib version: 2.1.2
  • Matplotlib backend (print(matplotlib.get_backend())): module://ipykernel.pylab.backend_inline
  • Python version: Python 3.6.4 |Anaconda custom (64-bit)
  • Jupyter version (if applicable): The version of the notebook server is: 5.3.1
  • Other libraries:

Activity

  1. added this to the milestone on Feb 1, 2018
  2. added
    Release criticalFor bugs that make the library unusable (segfaults, incorrect plots, etc) and major regressions.
    on Feb 1, 2018
  3. DizietAsahi commented on Feb 2, 2018

    @DizietAsahi
    Author

    Actually, I encountered this Exception in another context using seaborn.swarmplot, which showed me that the problem in the above code is actually not that the PathCollection is empty per se, but it is the clip_on=False that is causing problem.

    %matplotlib inline
    from matplotlib import pyplot as plt
    _, ax = plt.subplots()
    a = ax.scatter([], [], label='label', clip_on=False)
    ax.legend(handles=[a])
    
    plt.show()
    

    raises Exception ValueError
    but the very same code with clip_on=True does not

  4. modified the milestones: , on Feb 4, 2018
  5. removed
    Release criticalFor bugs that make the library unusable (segfaults, incorrect plots, etc) and major regressions.
    on Feb 4, 2018
  6. tacaswell commented on Feb 4, 2018

    @tacaswell
    Member

    punted to 3.0 as it is not the default code path that causes the issue.

  7. dstansby commented on Apr 8, 2018

    @dstansby
    Member

    @DizietAsahi could you try updating to Matplotlib version 2.2 and seeing if this is still an issue?

  8. modified the milestones: v3.0, v3.1 on Aug 11, 2018
  9. DizietAsahi commented on Oct 26, 2018

    @DizietAsahi
    Author

    The code

    %matplotlib inline
    from matplotlib import pyplot as plt
    _, ax = plt.subplots()
    a = ax.scatter([], [], label='label', clip_on=False)
    ax.legend(handles=[a])
    
    plt.show()
    

    still produces

    ValueError: cannot convert float NaN to integer
    < Figure size 432x288 with 1 Axes >

    with matplotlib 3.0.0, %matplotlib inline backend

  10. timhoffm commented on Oct 28, 2018

    @timhoffm
    Member

    Minimal example

    from matplotlib import pyplot as plt
    _, ax = plt.subplots()
    a = ax.scatter([], [], clip_on=False)
    plt.show()
    

    It does not happen with clip_on=True.

    The problem is that in

    def get_tick_space(self):

        def get_tick_space(self):
            ends = self.axes.transAxes.transform([[0, 0], [1, 0]])
            length = ((ends[1][0] - ends[0][0]) / self.axes.figure.dpi) * 72
            tick = self._get_tick(True)
            # There is a heuristic here that the aspect ratio of tick text
            # is no more than 3:1
            size = tick.label1.get_size() * 3
            if size > 0:
                return int(np.floor(length / size))
            else:
                return 2**31 - 1
    

    ends and thus length contains NaN.

    Not sure about the proper fix. Should transform yield something different or should we check for ends/length similar to the size > 0 check?

  11. jklymak commented on Oct 28, 2018

    @jklymak
    Member

    It might help to bisect to see what changed?

  12. modified the milestones: v3.1.0, v3.2.0 on Mar 18, 2019
  13. modified the milestones: v3.2.0, v3.3.0 on Aug 15, 2019
  14. QuLogic commented on May 7, 2020

    @QuLogic
    Member

    This was fixed in 3.0.3.

  15. modified the milestones: v3.3.0, v3.0.3 on May 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions