运行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()
错误原因
- 核心错误:直接调用
ax.images.append(im)是错误用法。ax.images是AxesImageList对象,它的append方法内部会尝试对传入对象做解包操作,但NonUniformImage实例无法被解包,因此抛出cannot unpack non-iterable NoneType object错误。 - 次要问题:代码缺少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
相关产品推荐
相关产品推荐

