使用matplotlib.pyplot.hist2d触发ValueError: too many values to unpack (expected 2)
使用matplotlib.pyplot.hist2d创建二维直方图时触发ValueError错误
问题详情
我正在学习Python绘图函数,使用matplotlib.pyplot.hist2d创建二维直方图时出现报错:ValueError: too many values to unpack (expected 2)。散点图可以正常显示,但二维直方图无法生成。
我的完整代码如下:
import numpy as np from numpy.random import seed from numpy.random import rand import matplotlib.pyplot as pit from mpl_toolkits.mplot3d import Axes3D X = [] y = [] X.append(rand(1)*100) Y.append(rand(1)*100) for i in range(1,10000): X.append(rand(1)*100) Y.append(X[i-1]) mu = np.mean(X) sigma = np.std(X) fig = pit.figure() axes = fig.subplots() axes.scatter(X, Y, s=.5) pit.show() print("X mean = {}\nX std dev = {}".format(mu, sigma)) x = np.array(X) plt.hist2d(X,Y, bins='auto') pit.show()
散点图输出结果:
X mean = 50.271585907067916
X std dev = 28.926289139289707
尝试改用axes.hist2d(X,Y, bins='auto')后仍出现相同错误,完整回溯信息:
AttributeError Traceback (most recent call last) /usr/share/jupyter/venvs/cognos-5.12.4/lib/python3.7/site-packages/numpy/lib/histograms.py in histogramdd(sample, bins, range, normed, weights, density) 1015 # Sample is an ND-array. 1016 N, D = sample.shape 1017 except (AttributeError, ValueError): AttributeError: 'list' object has no attribute 'shape' During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) /tmp/ipykernel_452/1275939754.py in <module> ---> 36 plt.hist2d(X,Y, bins='auto') 37 plt.show() /usr/share/jupyter/venvs/cognos-5.12.4/lib/python3.7/site-packages/matplotlib/pyplot.py in hist2d(x, y, bins, range, density, weights, cmin, cmax, data, **kwargs) 2625 x, y, bins=bins, range=range, density=density, 2626 weights=weights, cmin=cmin,cmax=cmax, ---> 2627 **({"data": data} if data is not None else {}), **kwargs) 2628 sci(_ret[-1]) 2629 return _ret /usr/share/jupyter/venvs/cognos-5.12.4/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs) 1412 def inner(ax, *args, data=None, **kwargs): 1413 if data is None: ---> 1414 return func(ax,*map(sanitize_sequence, args), **kwargs) 1415 1416 bound = new_sig.bind(ax, *args, **kwargs) /usr/share/jupyter/venvs/cognos-5.12.4/lib/python3.7/site-packages/matplotlib/axes/_axes.py in hist2d(self, x, y, bins, range, density, weights, cmin, cmax, **kwargs) 6981 6982 h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range, ---> 6983 density=density, weights=weights) 6984 6985 if cmin is not None: <_array_function_ internals> in histogram2d(*args, **kwargs) /usr/share/jupyter/venvs/cognos-5.12.4/lib/python3.7/site-packages/numpy/lib/twodim_base.py in histogram2d(x, y, bins, range, normed, weights, density) 749 xedges = yedges = asarray(bins) 750 ins = [xedges, yedges] ---> 751 hist, edges = histogramdd([x, y], bins, range, normed, weights, density) 752 return hist, edges[0], edges[1] <_array_function_ internals> in histogramdd(*args, **kwargs) /usr/share/jupyter/venvs/cognos-5.12.4/lib/python3.7/site-packages/numpy/lib/histograms.py in histogramdd(sample, bins, range, normed, weights, density) 1018 # Sample is a sequence of 1D arrays. 1019 sample = np.atleast_2d(sample).T ---> 1020 N, D = sample.shape 1021 1022 nbin = np.empty(D, int) ValueError: too many values to unpack (expected 2)
错误原因
- 数据结构错误:
rand(1)返回的是长度为1的numpy数组,直接存入列表后,X和Y变成了“数组的列表”,而非一维数值列表。hist2d无法正确解析这种嵌套结构,导致numpy在处理形状时触发错误。 - 别名混用:代码中导入matplotlib.pyplot时用了
pit作为别名,但后面调用plt.hist2d,属于未定义变量(实际运行中可能是笔误,但不影响核心错误)。
修复步骤
- 提取
rand(1)生成的标量值:用float()将数组转成单个数值,避免列表嵌套数组。 - 将列表转换为一维numpy数组:
hist2d对numpy数组的兼容性更好,能正确识别数据形状。 - 统一matplotlib别名:修正
pit为plt,避免变量混淆。
修复后完整代码
import numpy as np from numpy.random import rand import matplotlib.pyplot as plt X = [] Y = [] # 提取rand(1)的标量值,而非保留数组 X.append(float(rand(1)*100)) Y.append(float(rand(1)*100)) for i in range(1,10000): X.append(float(rand(1)*100)) Y.append(X[i-1]) # 转换为一维numpy数组 X = np.array(X) Y = np.array(Y) mu = np.mean(X) sigma = np.std(X) fig = plt.figure() axes = fig.subplots() axes.scatter(X, Y, s=.5) plt.show() print("X mean = {}\nX std dev = {}".format(mu, sigma)) # 生成二维直方图并添加颜色条 plt.hist2d(X,Y, bins='auto') plt.colorbar() plt.show()
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

