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

5
我正在尝试使用matplotlib.tri.Triangulation为matplotlib的plot_trisurf生成三角形。我想指定三角形而不是让Delaunay三角剖分来决定,因为在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()
1个回答

14
在matplotlib页面上有一个示例,展示了如何使用点和三角形来创建matplotlib.tri.Triangulation。由于这可能过于复杂,我们可以进一步简化。
让我们取4个点,这将创建2个三角形。 triangles参数将以点的索引形式指定三角形的角落。正如文档所说,

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

考虑以下代码,其中有一个(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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接