You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行numpy histogram2d示例时NonUniformImage报解包NoneType错误

numpy histogram2d示例代码报错:cannot unpack non-iterable NoneType object

问题代码

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()

错误原因

  1. 核心错误:直接调用ax.images.append(im)是错误用法。ax.images是AxesImageList对象,它的append方法内部会尝试对传入对象做解包操作,但NonUniformImage实例无法被解包,因此抛出cannot unpack non-iterable NoneType object错误。
  2. 次要问题:代码缺少numpy导入语句,import numpy as np未添加,会导致np.random.normal等numpy方法先触发未定义错误。

修复方法

  • 将报错行ax.images.append(im)替换为向坐标轴添加NonUniformImage的标准方法:
    ax.add_image(im)
    
  • 在代码开头补充numpy导入:
    import numpy as np
    from matplotlib.image import NonUniformImage
    import matplotlib.pyplot as plt
    

内容的提问来源于stack exchange,提问作者081N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:25:27