问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

使用 matplotlib.tri 库函数 可视化三角网格(含网格生成代码)

创作时间:
作者:
@小白创作中心

使用 matplotlib.tri 库函数 可视化三角网格(含网格生成代码)

引用
CSDN
1.
https://blog.csdn.net/qq_39538718/article/details/144473066

三角网格是有限元方法、数值模拟和计算机图形学中的基础工具之一。本文将介绍如何使用Python的matplotlib.tri模块来可视化三角网格,包括添加节点和单元编号、样式调整以及绘制质心等功能,使图形更加直观和美观。

背景与应用

在有限元分析中,三角网格常用于离散化复杂几何形状的区域,以便对偏微分方程进行数值求解。有效的网格可视化工具可以帮助用户:

  • 检查网格的生成质量。
  • 验证节点编号及边界条件的设置。
  • 对仿真结果进行后处理和展示。

这些操作能够在开发前期帮助研究人员快速进行代码调试和结果验证,对于提高工作效率很有帮助!

接下来,我们将通过代码示例展示如何实现这些功能。

代码概览

以下是一个使用matplotlib.tri绘制三角网格的Python脚本。代码包括了网格样式化、节点和单元编号的标注,以及对质心的计算和显示。

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

def plot_triangular_mesh(p, t):
    """
    根据节点坐标和三角形索引绘制三角网格,并进行样式化。
    参数:
    p (numpy.ndarray): 节点坐标,形状为 (n, 2)。
    t (numpy.ndarray): 三角形的节点索引,形状为 (m, 3)。
    """
    fig, ax = plt.subplots()
    # 创建 Triangulation 对象
    triang = tri.Triangulation(p[:, 0], p[:, 1], triangles=t)
    # 设置三角形颜色
    colors = 0.489 * np.ones(t.shape[0])
    ax.tripcolor(triang, facecolors=colors, cmap='Blues', edgecolors='black', linewidths=0.8)
    # 绘制红色节点
    ax.scatter(p[:, 0], p[:, 1], c='red', s=50, zorder=5)
    # 标注节点编号
    for i in range(p.shape[0]):
        ax.text(p[i, 0], p[i, 1], str(i), fontsize=10, ha='right', va='bottom', color='red')
    # 计算每个三角形的质心并标注单元编号
    centroids = np.mean(p[t], axis=1)
    for i in range(t.shape[0]):
        ax.text(centroids[i, 0], centroids[i, 1], str(i), fontsize=10, ha='center', va='center', color='black', fontweight='bold')
    # 设置坐标轴比例为等比例
    ax.set_aspect('equal')
    plt.grid(True)
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.title('带节点和单元编号的三角网格')
    plt.show()

# 示例数据
points = np.array([
    [0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]
])
triangles = np.array([
    [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]
])
plot_triangular_mesh(points, triangles)

代码解析

输入参数

  1. p: 节点的二维坐标,形状为 (n, 2)
points = np.array([
    [0, 0], [1, 0], [1, 1], [0, 1], [0.5, 0.5]
])
  1. t: 三角形的节点索引,形状为 (m, 3)
triangles = np.array([
    [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]
])

为了方便读者,这里也给出矩形区域三角网格生成代码:

import numpy as np
from scipy.spatial import Delaunay

def trimesh(x_start, x_end, y_start, y_end, n_x, n_y):
    # p: np*2,  t:nt*3
    h_x = (x_end - x_start) / n_x
    h_y = (y_end - y_start) / n_y
    X, Y = np.meshgrid(np.arange(x_start, x_end + h_x, h_x), np.arange(y_start, y_end + h_y, h_y))
    length = (n_x + 1) * (n_y + 1)
    x = X.flatten()
    y = Y.flatten()
    p = np.vstack((x, y)).T
    tri = Delaunay(p)
    t = tri.simplices
    return p, t

利用上述代码可以按照想要的分划粗细程度生成网格结构数据 [p,t]

主要实现

1. Triangulation 对象

使用 matplotlib.tri.Triangulation 创建三角剖分对象:

triang = tri.Triangulation(p[:, 0], p[:, 1], triangles=t)

2. 三角形着色

通过 ax.tripcolor 设置三角形颜色:

colors = 0.489 * np.ones(t.shape[0])

3. 节点和单元编号

使用 ax.text 在网格上添加节点编号(红色)和单元编号(黑色):

# 节点编号
ax.text(p[i, 0], p[i, 1], str(i), fontsize=10, ha='right', va='bottom', color='red')
# 单元编号
centroids = np.mean(p[t], axis=1)
ax.text(centroids[i, 0], centroids[i, 1], str(i), fontsize=10, ha='center', va='center', color='black', fontweight='bold')

可视化结果

运行脚本后,将看到:

  1. 带有黑色边界的三角网格。
  2. 红色的节点标记及其编号。
  3. 位于三角形中心的黑色单元编号。

自定义建议

  • 动态着色:根据三角形面积或节点值对网格进行着色。
  • 边界条件:对特定边界节点或单元添加不同的标注。
  • 布局优化:将网格可视化与仿真结果结合,生成更复杂的多视图布局。

数学公式

计算三角形质心的方法:

质心 = 1 3 ∑ i = 1 3 p i \text{质心} = \frac{1}{3} \sum_{i=1}^3 \mathbf{p}_i质心=31 i=1∑3 pi

总结

通过 matplotlib.tri,我们可以创建直观的三角网格图。这种可视化方法在数值仿真和图形展示中具有重要意义。读者可以尝试调整样式和标注(如网格背景,不同单元不同着色等等效果),以满足不同的应用需求。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号