三角形轮廓与meshgrid

时间:2011-04-03 00:17:58

标签: python numpy matplotlib

我正在尝试使用matplotlib和numpy为维基百科上的Dirichlet distribution重新创建图表(或者只是轮廓图可以)。我很难轻易生成三角形轮廓。第一个问题是meshgrid没有返回三角形的点。即使我得到一个三角形的点,contourf会处理非矩形输入吗?

这是我到目前为止所拥有的:

#!/usr/bin/env python
from __future__ import division
import matplotlib
matplotlib.use("TkAgg")
matplotlib.rc('text', usetex=True)
matplotlib.rcParams['text.latex.preamble']=r"""\usepackage{amsmath}
"""
import math
import scipy.special

root_three_over_two = np.sqrt(3) / 2

def new_figure():
    # 1.45
    plt.figure(figsize = [2.6, 2.6 * root_three_over_two], dpi = 1200)
    plt.axes([0.05, 0.10, 0.90, 0.90], frameon = False)

xsize = 1.0
ysize = root_three_over_two * xsize
plt.axis([0, xsize, 0, ysize])
resolution = 0.05

R = inclusive_arange(0.0, 1.0, resolution)
x, y = np.meshgrid(inclusive_arange(0.0, 1.0, resolution),
                   inclusive_arange(0.0, 1.0, resolution))
# UNFORTUNATELY x, and y include a lot of points where x+y>1
x = []
y = []
for yy in R:
    x.append(list(inclusive_arange(0.0, 1.0 - yy, resolution)))
    y.append([yy for xx in R])
print x
print y
z = 1 - x - y

# We can use these to convert to and from the equilateral triangle.
M = [[1, 0.5], [0, root_three_over_two]]
Mi = np.linalg.inv(M)

def dirichlet(x, y, z, a, b, c):
    if z < 0:
        return 0
    return x ** (a - 1) * y ** (b - 1) * z ** (c - 1) \
            * math.gamma(a + b + c) \
            / (math.gamma(a) * math.gamma(b) * math.gamma(c))

dirichlet = np.frompyfunc(dirichlet, 6, 1)

for (dirichlet_parm, filename) in [((5.0, 1.5, 2.5), "dir_small.pdf")]:
    new_figure()
    height = dirichlet(x, y, z, *dirichlet_parm)
    M = np.max(height)
    cs = plt.contourf(x, y, height, 50)
    S = sum(dirichlet_parm)
    plt.savefig(filename)

1 个答案:

答案 0 :(得分:2)

您不需要直线网格栅来创建等高线图。您可以定义周长并执行Delaunay三角剖分。当然,坐标仍然是直线的,并且(看起来)你需要进行转换。 This example应足以创建2D轮廓。我已经制作了一些带有非矩形周长的3D表面图,你会得到一些可能难看的边缘文物。一个非常精细的网格可能会改善其中的一些。