Python Matplotlib 用二维数组绘制 Hist2d

-1 投票
1 回答
11366 浏览
提问于 2025-04-18 07:17

我想通过传入两个大小相同的二维数组,Tx和alt_array(都是56000行,40列),来制作一个二维直方图。

def histo_2D(alt, Tx):  
u,v = 56000,40
Tx = np.zeros((u,v))
alt_array = np.zeros((u,v))
alt,tx = np.zeros((v)), np.zeros((v))
for i in range(0,v):
    alt[i] = i
    tx[i] = i
alt_array[:][:] = alt 
Tx[:][:] = tx
    alt_array[:][:] = alt 
    print np.shape(Tx), np.shape(alt_array)
    plt.hist2d(Tx , alt_array)

但是当我尝试运行我的程序时,出现了这个错误信息:

Traceback (most recent call last):
  File "goccp.py", line 516, in <module>
    histo_2D(alt,Tx)
  File "goccp.py", line 376, in histo_2D
    plt.hist2d(Tx , alt_array)
  File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2847, in hist2d
    weights=weights, cmin=cmin, cmax=cmax, **kwargs)
  File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 8628, in hist2d
    normed=normed, weights=weights)
  File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/twodim_base.py", line 650, in histogram2d
    hist, edges = histogramdd([x, y], bins, range, normed, weights)
  File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py", line 288, in histogramdd
    N, D = sample.shape
ValueError: too many values to unpack

我试着使用扁平化的数组,但结果并不是很好……

1 个回答

2

关于 hist2d 的说明提到:

matplotlib.pyplot.hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, **kwargs)

参数: x, y: 类似数组的东西,形状为 (n, ) :

所以 xy 需要是一维的;而你的值是二维的。

另外,文档最后还有一个例子,可以看看。

撰写回答