使用 Matplotlib 创建交互式三角剖分图

PythonPythonBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

本实验将指导你使用 Matplotlib 创建三角剖分图。你将学习如何创建 Triangulation 对象、使用 TriFinder 对象以及设置交互性以突出显示光标下方的三角形。

虚拟机提示

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

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

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

创建三角剖分对象

首先,我们需要创建一个三角剖分对象。我们将使用 matplotlib.tri 中的 Triangulation 类。在这个例子中,我们将用随机数据创建一个三角剖分对象。

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

## 生成随机数据
x = np.random.rand(10)
y = np.random.rand(10)
triang = Triangulation(x, y)

创建 TriFinder 对象

为了找到光标下方的三角形,我们需要创建一个 TriFinder 对象。我们可以使用 get_trifinder() 方法从三角剖分对象中获取默认的 TriFinder 对象。

trifinder = triang.get_trifinder()

设置绘图

现在,我们可以设置绘图了。我们将使用 plt.subplots() 创建一个图形和轴对象。然后,我们将使用 ax.triplot() 绘制三角剖分图。

fig, ax = plt.subplots()
ax.triplot(triang)

突出显示光标下方的三角形

当鼠标在绘图区域移动时,我们希望突出显示光标下方的三角形。为此,我们将创建一个 Polygon 对象,该对象将使用光标下方三角形的顶点进行更新。我们将使用 ax.add_patch() 将多边形添加到绘图中。

from matplotlib.patches import Polygon

polygon = Polygon([[0, 0], [0, 0], [0, 0]], facecolor='y')
ax.add_patch(polygon)

我们还将创建一个函数 update_polygon(),该函数将使用光标下方三角形的顶点更新多边形的顶点。

def update_polygon(tri):
    if tri == -1:
        points = [0, 0, 0]
    else:
        points = triang.triangles[tri]
    xs = triang.x[points]
    ys = triang.y[points]
    polygon.set_xy(np.column_stack([xs, ys]))

设置交互性

我们需要设置交互性来更新光标下方的三角形。我们将使用 motion_notify_event 来检测鼠标何时在绘图区域上移动。我们将创建一个函数 on_mouse_move(),该函数将使用 TriFinder 对象获取光标下方的三角形,用三角形的顶点更新多边形,并使用三角形的索引更新绘图标题。

def on_mouse_move(event):
    if event.inaxes is None:
        tri = -1
    else:
        tri = trifinder(event.xdata, event.ydata)
    update_polygon(tri)
    ax.set_title(f'Triangle {tri}')
    event.canvas.draw()

fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)

显示绘图

最后,我们可以使用 plt.show() 来显示绘图。

plt.show()

总结

在本实验中,我们学习了如何使用 Matplotlib 创建三角剖分图。我们使用 TriangulationTriFinder 类来创建三角剖分并找到光标下方的三角形。我们还设置了交互性以突出显示光标下方的三角形。