2011-04-03 161 views
0

我試圖重新使用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) 
+0

什麼是數字模塊? – Paul 2011-04-03 04:55:29

+0

@Paul:我自己的幫助函數模塊。我會刪除它。 – 2011-04-03 18:21:23

回答

2

你不需要直線meshgrid創建一個等高線圖。您可以定義邊界並執行Delaunay三角測量。當然,座標仍然是直線的,(看起來)你需要做一個轉換。 This example應該足以創建2D輪廓。我製作了一些非矩形外圍的三維表面圖,並且您會看到一些可能不美觀的邊緣工件。一個非常好的網格可能會改善其中的一些。

+0

謝謝,'tricontourf'正是我所需要的。 Delaunay三角測量功能還簡化了代碼。你用'plot_surface'來繪製你的3d曲面嗎? – 2011-04-04 00:17:11

+0

@ Neil G:是的。然而,我沒有嘗試'plot_wireframe'。這可能會更好看。 – Paul 2011-04-04 01:03:59