用对应于 Python 中的 X、Y 和 Z 的三个不同数组构建等高线图

Constructing a Contour Plot with Three Different Arrays Corresponding to X, Y, and Z in Python

如果我有特定的 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 值,我可以将此等高线图与第一个等高线图一起绘制吗?

我认为你需要做一个插值:

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')

这给出:

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

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

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()

这是输出: