用离散数据的水平绘制轮廓

时间:2014-02-14 16:38:47

标签: python matplotlib

我有三个参数x,y和z,每个参数有61个值。我想创建一个等级为0.5,-2.3,-4.61,-9.21的等高线图。问题是Z是1D,它应该是2D数组。如何在我自己的数据上使用griddata?

import numpy as np
import matplotlib.pyplot as plt
x=[4, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10]
y=[-6.95138e-06, -9.09998e-07, 8.24384e-06, 3.4941e-06, 5.08276e-06, 7.82652e-06, -4.7378e-06, -1.40027e-05, -1.62638e-05, -3.97604e-06, 3.19294e-06, 2.50123e-06, -4.13063e-06, -6.60289e-06, -4.02982e-06, -2.32882e-06, -3.86464e-06, -1.09167e-05, -9.42387e-06, -3.48118e-07, 5.22e-06, 8.74445e-06, 1.35842e-05, 2.33632e-05, 2.71328e-05, 1.747e-05, 2.32177e-06, -7.25386e-06, -9.75881e-06, -2.99633e-06, 1.19281e-06, -4.24077e-06, -7.4252e-06, -4.54435e-07, 1.03078e-05, 1.14579e-05, 3.90613e-06, -4.77174e-06, -9.25321e-06, -8.36579e-06, -3.0257e-06, -1.69309e-06, -5.36534e-06, -4.01092e-06, 1.20577e-06, 5.13284e-06, 5.06792e-06, 4.81178e-06, 5.9607e-06, 6.70492e-06, 3.45118e-06, 2.51942e-06, 1.23012e-06, 2.09802e-06, 1.44658e-06, -8.93274e-08, -5.14753e-06, -9.93717e-06, -7.91692e-06, -4.12816e-06, -6.33457e-06]
X, Y = np.meshgrid(x, y)
Z=[-0.63, -0.02, -1.05, -0.22, -0.51, -1.26, -0.53, -4.97, -7.32, -0.44, -0.30, -0.19, -0.55, -1.48, -0.58, -0.20, -0.57, -5.00, -3.84, -0.01, -1.17, -3.31, -8.13, -22.59, -30.52, -13.69, -0.27, -2.88, -5.48, -0.49, -0.08, -0.86, -2.94, -0.01, -4.32, -5.49, -0.69, -1.15, -4.70, -3.73, -0.44, -0.14, -1.49, -0.77, -0.07, -1.08, -1.04, -0.93, -1.42, -1.76, -0.51, -0.25, -0.07, -0.18, -0.09, -0.00, -1.08, -5.03, -2.64, -0.65, -1.65]
plt.figure()
levels = [0.5, -2.3, -4.61, -9.21]
contour = plt.contour(X, Y, Z, levels)

修改

我使用griddata作为以下

xi = np.linspace(min(x), max(x), 30)
yi = np.linspace(min(y), max(y), 30)
[X, Y] = np.meshgrid(xi, yi)
Z = np.griddata(x, y, z, X, Y)

但它给了我这个错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 File "/usr/lib64/python2.7/site-packages/matplotlib/mlab.py", line 2775, in griddata
 tri = delaunay.Triangulation(x,y)
 File "/usr/lib64/python2.7/site-packages/matplotlib/delaunay/triangulate.py", line 123, in __init__
 self.hull = self._compute_convex_hull()
 File "/usr/lib64/python2.7/site-packages/matplotlib/delaunay/triangulate.py", line 158, in _compute_convex_hull
hull.append(edges.pop(hull[-1]))
 KeyError: 0

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

等高线图需要三个变量;每个(x,y)点都有一个必须与之关联的高度(z)。如果您只有高度但数据结构为2D网格,则可以使用plt.contour。如果数据是非结构化的,您可以使用scipy.griddatainterpolate it first然后应用轮廓。