当前位置:  开发笔记 > 编程语言 > 正文

numpy轮廓:TypeError:输入z必须是2D数组

如何解决《numpy轮廓:TypeError:输入z必须是2D数组》经验,为你挑选了1个好方法。

我有列表格式列表中的数据。

看起来像这样:

[(x_1, y_1, Z_1),...(x_i, y_j, z_k),...(x_p, y_q, z_r)]

对于每个x和y,都有一个z。X,Y和Z的长度分别为p,q和r(= p * q)。

我打算绘制一个轮廓图,其中X和Y为网格,Z为要绘制的值。

我有以下代码(仅代表):

import csv
import sys
import statistics
import numpy as np
from scipy.interpolate import UnivariateSpline
from matplotlib import pyplot as plt
...........

#format of data = [(x, y, z)......]

#x, y, z are lists

X = [X1,..........,Xp] #length, p 

Y = [Y1,..........,Yq] #length, q

Z = [Z1,..........,Zpq] #length, pq

#np.mesh

X1, Y1 = np.meshgrid(X, Y)

plt.figure()
CS = plt.contour(X1, Y1, Z)
plt.clabel(CS, inline=1, fontsize=10)

我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/gakadam/PycharmProjects/waferZoning/contour.py", line 49, in 
    CS = plt.contour(X1, Y1, Z)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\pyplot.py", line 2766, in contour
    ret = ax.contour(*args, **kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\__init__.py", line 1811, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\axes\_axes.py", line 5640, in contour
    return mcontour.QuadContourSet(self, *args, **kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\contour.py", line 1428, in __init__
    ContourSet.__init__(self, ax, *args, **kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\contour.py", line 873, in __init__
    self._process_args(*args, **kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\contour.py", line 1445, in _process_args
    x, y, z = self._contour_args(args, kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\contour.py", line 1532, in _contour_args
    x, y, z = self._check_xyz(args[:3], kwargs)
  File "C:\Users\gakadam\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\contour.py", line 1566, in _check_xyz
    raise TypeError("Input z must be a 2D array.")
TypeError: Input z must be a 2D array.

我知道错误是什么,但我无法纠正。

我不能提供MWE,但我想我已经很清楚地说明了我的问题。

https://www.dropbox.com/s/33jmfcjzikl4w5g/contour_synthetic.txt?dl=0



1> Mike Müller..:

你需要有一个z 有长度等于长度的产品xy

assert len(z) == (len(x) * len(y))

制作z二维数组:

z = np.array(z)
z = z.reshape((len(x), len(y)))

这是MCVE:

x = np.arange(5)
y = np.arange(5)
z = np.arange(25).reshape(5, 5)
x1, y1 = np.meshgrid(x, y)
plt.contour(x1, y1, z)

确保您的数据的结构如下。

推荐阅读
ERIK又
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有