使用scipy.spatial.Delaunay代替matplotlib.tri.Triangulation的内置版本

时间:2014-03-26 07:13:43

标签: python matplotlib scipy delaunay

似乎matplotlib.tri.Triangulation使用了错误且可能不正确的Delaunay三角测量实现,该实现将由qHull替换。

我试图使用mpl_toolkits.mplot3d.plot_trisurf()绘制一个trisurf并遇到一堆无用的异常(IndexErrorKeyError s,但没有任何迹象表明完全出错了)。

由于scipy.spatial.Delaunay已经使用了qHull,我想知道是否有办法使用scipy实现Delaunay三角剖分来构建matplotlib.tri.Triangulation对象以供mpl_toolkits.mplot3d.plot_trisurf()使用。< / p>

我已尝试通过delaunay.points参数将matplotlib.tri.Triangulate直接传递给triangles,但这会产生ValueError: triangles min element is out of bounds

1 个答案:

答案 0 :(得分:6)

http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.spatial.Delaunay.html http://matplotlib.org/dev/api/tri_api.html

所以你需要将qhull中的点和三角形传递给Triangulation构造函数:

import numpy as np
import scipy.spatial
import matplotlib
import math

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

# First create the x and y coordinates of the points.
n_angles = 20
n_radii = 10
min_radius = 0.15
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi/n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()

# Create the Delaunay tessalation using scipy.spatial
pts = np.vstack([x, y]).T
tess = scipy.spatial.Delaunay(pts)

# Create the matplotlib Triangulation object
x = tess.points[:, 0]
y = tess.points[:, 1]
tri = tess.vertices # or tess.simplices depending on scipy version
triang = mtri.Triangulation(x=pts[:, 0], y=pts[:, 1], triangles=tri)

# Plotting
z = x*x + y*y
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(triang, z)
plt.show()

输出(使用matplotlib当前主站): enter image description here