不规则数据网格等高线绘制

Beginner

This tutorial is from open-source community. Access the source code

简介

本实验展示了如何使用 Matplotlib 在 Python 中创建不规则间隔数据的等高线图。等高线图使用等值线或等高线显示数据值的二维分布。在本示例中,我们将比较在规则网格上插值的不规则间隔数据的等高线图与非结构化三角形网格的三角等高线图。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。

导入必要的库

我们首先导入本示例所需的库:matplotlib.pyplotnumpy。此外,我们导入 matplotlib.tri 用于数据的三角剖分。

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

生成随机数据

我们使用 NumPy 的 np.random.uniform 方法生成随机数据。我们生成 npts = 200 个数据点,其 x 和 y 值在 -2 到 2 之间。我们还使用函数 z = x * np.exp(-x**2 - y**2) 计算 z 值。

np.random.seed(19680801)
npts = 200
x = np.random.uniform(-2, 2, npts)
y = np.random.uniform(-2, 2, npts)
z = x * np.exp(-x**2 - y**2)

在网格上进行插值

我们通过在网格上进行插值来创建不规则间隔数据坐标的等高线图。我们首先使用 np.linspace 创建 x 和 y 的网格值。然后,我们使用 tri.LinearTriInterpolator 在由 (xi, yi) 定义的网格上对数据 (x, y) 进行线性插值。我们使用常规的 axes.Axes.contour 绘制插值后的数据。

ngridx = 100
ngridy = 200
xi = np.linspace(-2.1, 2.1, ngridx)
yi = np.linspace(-2.1, 2.1, ngridy)

triang = tri.Triangulation(x, y)
interpolator = tri.LinearTriInterpolator(triang, z)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)

fig, ax1 = plt.subplots()
cntr1 = ax1.contourf(xi, yi, zi, levels=14, cmap="RdBu_r")
ax1.plot(x, y, 'ko', ms=3)
ax1.set(xlim=(-2, 2), ylim=(-2, 2))
ax1.set_title('Contour Plot of Irregularly Spaced Data Interpolated on a Grid')
fig.colorbar(cntr1, ax=ax1)
plt.show()

三角等高线图

我们通过直接将无序、不规则间隔的坐标提供给 axes.Axes.tricontour,使用三角等高线图绘制相同的数据。

fig, ax2 = plt.subplots()
cntr2 = ax2.tricontourf(x, y, z, levels=14, cmap="RdBu_r")
ax2.plot(x, y, 'ko', ms=3)
ax2.set(xlim=(-2, 2), ylim=(-2, 2))
ax2.set_title('Tricontour Plot of Irregularly Spaced Data')
fig.colorbar(cntr2, ax=ax2)
plt.show()

总结

本实验展示了如何使用 Matplotlib 在 Python 中创建不规则间隔数据的等高线图。我们比较了在规则网格上插值的不规则间隔数据的等高线图与非结构化三角形网格的三角等高线图。使用 axes.Axes.contouraxes.Axes.tricontour 方法创建等高线图。