使用 matplotlib.tri.Triangulation 创建在 Matplotlib 的plot_trisurf 中使用的三角剖分

2023-12-09

我是一个尝试使用matplotlib.tri.Triangulation为 matplotlibs 生成三角形plot_trisurf。我想指定三角形而不是让 Delaunay 三角剖分matplotlib.tri.Triangulation使用是因为它不适用于某些情况,例如 xz 或 yz 平面中的三角形。我不确定自己指定三角形是否可以解决问题,但我似乎是一个值得尝试的好事情。

问题是三角剖分需要一个 (n,3) 数组,其中 n 是三角形的数量。引用 matplotlib.org 上的页面“对于每个三角形,组成三角形的三个点的索引,以逆时针方式排序。”https://matplotlib.org/api/tri_api.html#matplotlib.tri.Triangulation。我无法辨别如何以正确的形式创建数组,那就是我需要帮助。我很感激任何帮助。

到目前为止我已经尝试了一些事情,但这是我最后一次尝试的样子:

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

fig = plt.figure()
ax = fig.gca(projection='3d')

x1=0
x2=1
x3=1
x4=0

y1=0
y2=0
y3=2
y4=2

x=[]
y=[]
x.append(x1)
x.append(x2)
x.append(x3)
x.append(x4)
y.append(y1)
y.append(y2)
y.append(y3)
y.append(y4)
z=np.zeros(8)

triang = mtri.Triangulation(x, y, triangles=[[[x1,y1],[x2,y2],[x3,y3]],[[x3,y3],[x4,y4],[x2,y2]]])

ax.plot_trisurf(triang, z, linewidth=0.2, antialiased=True)

ax.view_init(45,-90)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_aspect("equal")

fig.set_size_inches(8,8)

plt.show()

一个例子在 matplotlib 页面上展示了如何使用点和三角形来创建matplotlib.tri.Triangulation。由于这可能不必要地复杂,我们可以进一步简化。

我们取 4 个点,这将创建 2 个三角形。这triangles参数将以点索引的形式指定三角形的角。正如文档所说,

triangles:形状为 (ntri, 3) 的整数 array_like,可选
对于每个三角形,组成三角形的三个点的索引按逆时针方式排序。 [..]

考虑这段代码,其中我们有一个 (4,2) 数组,指定点坐标,具有一行中每个点的 x 和 y 坐标。然后,我们通过使用应以逆时针方式构成三角形的点的索引来创建三角形。

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

xy = [[0.3,0.5],
      [0.6,0.8],
      [0.5,0.1],
      [0.1,0.2]]
xy = np.array(xy)

triangles = [[0,2,1],
             [2,0,3]]

triang = mtri.Triangulation(xy[:,0], xy[:,1], triangles=triangles)
plt.triplot(triang, marker="o")

plt.show()

第一个三角形由点组成0, 2, 1和第二个2,0,3。下图显示了该代码的可视化。

enter image description here

然后我们可以创建一个列表z值和 3D 绘图相同。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
from mpl_toolkits.mplot3d import Axes3D

xy = [[0.3,0.5],
      [0.6,0.8],
      [0.5,0.1],
      [0.1,0.2]]
xy = np.array(xy)

triangles = [[0,2,1],
             [2,0,3]]

triang = mtri.Triangulation(xy[:,0], xy[:,1], triangles=triangles)

z = [0.1,0.2,0.3,0.4]

fig, ax = plt.subplots(subplot_kw =dict(projection="3d"))
ax.plot_trisurf(triang, z)

plt.show()

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 matplotlib.tri.Triangulation 创建在 Matplotlib 的plot_trisurf 中使用的三角剖分 的相关文章

随机推荐