Matplotlib 类似于 matlab 的 trisurf [英] Matplotlib like matlab's trisurf
问题描述
长话短说,我想在 python 中绘制一个通用的 3D 三角形网格.Matplotlib 似乎是理想的候选者,但我会选择任何可以完成我将要描述的内容的 3D 渲染.
To make a long story short, I'd like to plot a generic 3D triangle mesh in python. Matplotlib seems to be the ideal candidate, but I'd go with any 3D rendering that can do what I'm about to describe.
假设我有一个由 X、Y 和 Z 定义的三角形网格,点云的 3D 坐标,每个都是一个长度为 n 的向量,以及 UVW,一个 2D mx-3 矩阵,其中每一行是索引到点云中.这个三元组代表一个单独的三角形.换句话说,我在 n 个点上有 m 个三角形.在 Matlab 中,要生成 3D 图,我只需要:
Suppose I have a triangle mesh defined by X, Y, and Z, the 3D coordinates of a point cloud, each a vector of length n, and UVW, a 2D m-x-3 matrix in which each row is a triplet of indices into the point cloud. This triplet represents an individual triangle. In other words, I have m triangles over n points. In Matlab, to generated a 3D plot, I just do:
trisurf(UVW, X, Y, Z)
有人有这方面的经验吗?特别是,mplots trisurf 可以硬着头皮工作吗?
Does anyone have any experience with this? In particular, can mplots trisurf be shoehorned to work?
推荐答案
根据您的性能需求,mayavi 可能最适合于此 - 根据 Davis 的评论.
Depending on your performance needs, mayavi is likely to be best suited for this - as per Davis comment.
但是,matplotlib 带有 plot_trisurf 您可以完美地将通用的 UVW
、X
、Y
、Z
传递给您所描述的.
However, matplotlib comes with plot_trisurf to which you can perfectly pass generic UVW
, X
, Y
, Z
as you describe.
具有圆环网格的示例:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
R = 1.
r = 0.8
n = 50
m = 50
def torus_triangles(n, m):
""" Returns triangles to mesh a (n, m) torus """
tri = []
for i in range(n):
for j in range(m):
a = i + j*(n)
b = ((i+1) % n) + j*n
d = i + ((j+1) % m) * n
c = ((i+1) % n) + ((j+1) % m) * n
tri += [[a, b, d], [b, c, d]]
return np.array(tri, dtype=np.int32)
theta0 = np.linspace(0, (2*np.pi), n, endpoint=False)
phi0 = np.linspace(0, (2*np.pi), m, endpoint=False)
theta, phi = np.meshgrid(theta0, phi0)
x = (R + r * np.sin(phi)) * np.cos(theta)
y = (R + r * np.sin(phi)) * np.sin(theta)
z = r * np.cos(phi)
triangles = torus_triangles(n , m)
triang = mtri.Triangulation(x.ravel(), y.ravel(), triangles)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_trisurf(triang, z.ravel(), lw=0.2, edgecolor="black", color="grey",
alpha=0.5)
plt.show()
这篇关于Matplotlib 类似于 matlab 的 trisurf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!