在Python中构造一个与X,Y和Z对应的三个不同数组的轮廓图

时间:2016-12-12 01:44:22

标签: python arrays matplotlib grid contour

如果我有特定的x和y值对应于由数组分隔的z值,我将如何制作等高线图?例如:

Array 1 (X):
1
4
6
7
8
2
6

Array 2 (Y):
7
7
8
9
0
1
2

Array 3 (Z):
8
9 
7
1
2
2
3

我是否必须做X1,Y1 = np.meshgrid(X,Y)并以某种方式塑造Z数组?有没有使用meshgrid的另一种方法吗?另外,如果我添加第四个数组并将其命名为Z1,并且具有与特定Z1相对应的相同x和y值,我可以将该等高线图与第一个等值线图一起绘制吗?

2 个答案:

答案 0 :(得分:2)

如果没有规则网格,使用三角形表面插值可能是一个不错的选择。

在这个例子和上面的例子中,如果你有更长的数据,你只需要检查图的边界。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.tri as tri

sns.set(style="white")

x = np.array([1,4,6,7,8,2,6])
y = np.array([7,7,8,9,0,1,2])
z = np.array([8,9,7,1,2,2,3])

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)

nptsx, nptsy = 100, 100
xg, yg = np.meshgrid(np.linspace(x.min(), x.max(), nptsx),
                     np.linspace(y.min(), y.max(), nptsy))

triangles = tri.Triangulation(x, y)
tri_interp = tri.CubicTriInterpolator(triangles, z)
zg = tri_interp(xg, yg)

# change levels here according to your data
levels = np.linspace(0, 10, 5)
colormap = ax.contourf(xg, yg, zg, levels,
                       cmap=plt.cm.Blues,
                       norm=plt.Normalize(vmax=z.max(), vmin=z.min()))

# plot data points
ax.plot(x, y, color="#444444", marker="o", linestyle="", markersize=10)

# add a colorbar
fig.colorbar(colormap,
             orientation='vertical',  # horizontal colour bar
             shrink=0.85)

# graph extras: look at xlim and ylim
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
ax.set_aspect("equal", "box")

plt.show()

这是输出:

enter image description here

答案 1 :(得分:1)

我认为你需要进行插值:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from scipy import interpolate
x = np.array([1,4,6,7,8,2,6])
y = np.array([7,7,8,9,0,1,2])
z = np.array([8,9,7,1,2,2,3])
points = np.column_stack((x,y))
values = z.T

gridx, gridy = np.mgrid[0:8:100j, 0:8:100j]
gridz = interpolate.griddata(points, values, (gridx, gridy), method='cubic')

fig = plt.figure(figsize=(12,5))

ax1 = fig.add_subplot(121,projection='3d')
ax1.plot3D(x,y,z, 'k.', ms=10)
ax1.contour(gridx,gridy,gridz)

ax2 = fig.add_subplot(122,projection='3d')
ax2.plot3D(x,y,z, 'k.', ms=10)
ax2.plot_wireframe(gridx, gridy, gridz,rstride=5,cstride=5)
plt.savefig('contour_wire.png')

这给出了:

enter image description here