pythonnumpyhistogram2d

NonUniformImage: numpy example gives 'cannot unpack non-iterable NoneType object' error 2D-Histogram


I'm trying to run this very simple example from numpy page regarding histogram2d:

https://numpy.org/doc/stable/reference/generated/numpy.histogram2d.html.

from matplotlib.image import NonUniformImage
import matplotlib.pyplot as plt
xedges = [0, 1, 3, 5]
yedges = [0, 2, 3, 4, 6]

x = np.random.normal(2, 1, 100)
y = np.random.normal(1, 1, 100)
H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
H = H.T
fig = plt.figure(figsize=(7, 3))
ax = fig.add_subplot(131, title='imshow: square bins')
plt.imshow(H, interpolation='nearest', origin='lower',extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
ax = fig.add_subplot(132, title='pcolormesh: actual edges',aspect='equal')
X, Y = np.meshgrid(xedges, yedges)
ax.pcolormesh(X, Y, H)
ax = fig.add_subplot(133, title='NonUniformImage: interpolated',aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
im = NonUniformImage(ax, interpolation='bilinear')
xcenters = (xedges[:-1] + xedges[1:]) / 2
ycenters = (yedges[:-1] + yedges[1:]) / 2
im.set_data(xcenters,ycenters,H)
ax.images.append(im)
plt.show()

By running this code as in the example, I receive the error

cannot unpack non-iterable NoneType object

This happens as soon as I run the line ax.images.append(im).

Does anyone know why this happens?

Tried to run an example from numpy website and doesn't work as expected.


Solution

  • The full error message is:

    TypeError                                 Traceback (most recent call last)
    File ~\anaconda3\lib\site-packages\IPython\core\formatters.py:339, in BaseFormatter.__call__(self, obj)
        337     pass
        338 else:
    --> 339     return printer(obj)
        340 # Finally look for special method names
        341 method = get_real_method(obj, self.print_method)
    
    File ~\anaconda3\lib\site-packages\IPython\core\pylabtools.py:151, in print_figure(fig, fmt, bbox_inches, base64, **kwargs)
        148     from matplotlib.backend_bases import FigureCanvasBase
        149     FigureCanvasBase(fig)
    --> 151 fig.canvas.print_figure(bytes_io, **kw)
        152 data = bytes_io.getvalue()
        153 if fmt == 'svg':
    
    File ~\anaconda3\lib\site-packages\matplotlib\backend_bases.py:2299, in FigureCanvasBase.print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, pad_inches, bbox_extra_artists, backend, **kwargs)
       2297 if bbox_inches:
       2298     if bbox_inches == "tight":
    -> 2299         bbox_inches = self.figure.get_tightbbox(
       2300             renderer, bbox_extra_artists=bbox_extra_artists)
       2301         if pad_inches is None:
       2302             pad_inches = rcParams['savefig.pad_inches']
    
    File ~\anaconda3\lib\site-packages\matplotlib\figure.py:1632, in FigureBase.get_tightbbox(self, renderer, bbox_extra_artists)
       1629     artists = bbox_extra_artists
       1631 for a in artists:
    -> 1632     bbox = a.get_tightbbox(renderer)
       1633     if bbox is not None and (bbox.width != 0 or bbox.height != 0):
       1634         bb.append(bbox)
    
    File ~\anaconda3\lib\site-packages\matplotlib\axes\_base.py:4666, in _AxesBase.get_tightbbox(self, renderer, call_axes_locator, bbox_extra_artists, for_layout_only)
       4662     if np.all(clip_extent.extents == axbbox.extents):
       4663         # clip extent is inside the Axes bbox so don't check
       4664         # this artist
       4665         continue
    -> 4666 bbox = a.get_tightbbox(renderer)
       4667 if (bbox is not None
       4668         and 0 < bbox.width < np.inf
       4669         and 0 < bbox.height < np.inf):
       4670     bb.append(bbox)
    
    File ~\anaconda3\lib\site-packages\matplotlib\artist.py:355, in Artist.get_tightbbox(self, renderer)
        340 def get_tightbbox(self, renderer):
        341     """
        342     Like `.Artist.get_window_extent`, but includes any clipping.
        343 
       (...)
        353         The enclosing bounding box (in figure pixel coordinates).
        354     """
    --> 355     bbox = self.get_window_extent(renderer)
        356     if self.get_clip_on():
        357         clip_box = self.get_clip_box()
    
    File ~\anaconda3\lib\site-packages\matplotlib\image.py:943, in AxesImage.get_window_extent(self, renderer)
        942 def get_window_extent(self, renderer=None):
    --> 943     x0, x1, y0, y1 = self._extent
        944     bbox = Bbox.from_extents([x0, y0, x1, y1])
        945     return bbox.transformed(self.axes.transData)
    
    TypeError: cannot unpack non-iterable NoneType object
    <Figure size 504x216 with 3 Axes>
    

    The error occurs deep in the append call, and appears to involve trying to get information about the plot window. If I comment out the append line, and it continues on to the plt.show(), and resulting image looks like the example, except the third image is blank.

    enter image description here

    I tested this in a Windows QtConsole; I don't know if that context posses problems for this append or not. I don't think it's a problem with your code copy.