我在列表格式列表中有数据。
看起来像这样:
[(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 <module>
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
答案 0 :(得分:6)
您需要z
,其长度为x
和y
的长度:
assert len(z) == (len(x) * len(y))
使z
成为2D数组:
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)
确保您的数据结构如下。