如何使用matplotlib在3D中绘制三角形?

时间:2019-07-16 11:36:23

标签: python matplotlib 3d

给出如下列表:

triangels =  [
((1,1,1),(2,2,2),(1,3,4)),
((2,3,4),(9,9,9),(3,4,5)),
]

使用pyplot在3D中绘制两个三角形的最快方法是什么?我找不到任何方法,有2D实现。

谢谢!

这不是重复的,因为我问过如何将给定的列表转换成三角形,我没有要求输入已经被操纵的解决方案。

2 个答案:

答案 0 :(得分:3)

这是一种更简单的方法

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

triangles =  [
((1,1,1),(2,2,2),(1,3,4)),
((2,3,4),(9,9,9),(3,4,5)),
]


ax = plt.gca(projection="3d")

ax.add_collection(Poly3DCollection(triangles))

ax.set_xlim([0,10])
ax.set_ylim([0,10])
ax.set_zlim([0,10])

plt.show()

enter image description here

答案 1 :(得分:1)

这是一种简单的方法:

from itertools import chain
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

triangles =  [
    ((1, 1, 1), (2, 2, 2), (1, 3, 4)),
    ((2, 3, 4), (9, 9, 9), (3, 4, 5)),
]

# Convert the list of triangles into a "flat" list of points
tri_points = list(chain.from_iterable(triangles))
# Get the X, Y and Z coordinates of each point
x, y, z = zip(*tri_points)
# Make list of triangle indices ([(0, 1, 2), (3, 4, 5), ...])
tri_idx = [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(len(triangles))]
# Make 3D axes
ax = plt.figure().gca(projection='3d')
# Plot triangles
ax.plot_trisurf(x, y, z, triangles=tri_idx)

结果:

Result

相关问题