Skip to main content
 首页 » 编程设计

python之将 NumPy 二维阵列中的所有二维点连接为三角形网格

2024年10月25日6davidwang456

我是 Python 的新手,我正在尝试绘制这样的三角形网格:

import matplotlib.pyplot as plt 
import numpy as np 
 
r   = 0.25 
d   = 2*r 
s   = 0 
 
l1 = np.array([[s,0], [s+d,0], [s+2*d,0], [s+3*d,0]])  
l2 = np.array([[s-r,d], [s+r,d], [s+r+d,d], [s+r+2*d,d]]) 
l3 = np.array([[s,2*d], [s+d,2*d], [s+2*d,2*d], [s+3*d,2*d]]) 
l4 = np.array([[s-r,3*d], [s+r,3*d], [s+r+d,3*d], [s+r+2*d,3*d]]) 
l5 = np.array([[s,4*d], [s+d,4*d], [s+2*d,4*d], [s+3*d,4*d]]) 
 
plt.scatter(*zip(*l1)) 
plt.scatter(*zip(*l2)) 
plt.scatter(*zip(*l3)) 
plt.scatter(*zip(*l4)) 
plt.scatter(*zip(*l5)) 
 
plt.show 

我的问题是,我不知道如何连接所有点。我为所有 l 添加了带有 plt.plot(*zip(*l1)) 的水平线,但我不知道如何绘制“垂直”之字形线。 . 有人有“简单”的解决方案吗?

非常感谢!

请您参考如下方法:

triplot是为此目的而制作的:绘制三角形。 您可以只传递 x 和 y 坐标(在这种情况下将计算 Delaunay 三角剖分),或者传递一个完整的 Triangulation 对象可以指定自己的三角形。

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.tri as mtri 
 
r = 0.25 
d = 2*r 
s = 0 
 
def meshgrid_triangles(n, m): 
    """ Returns triangles to mesh a np.meshgrid of n x m points """ 
    tri = [] 
    for i in range(n-1): 
        for j in range(m-1): 
            a = i + j*(n) 
            b = (i+1) + j*n 
            d = i + (j+1)*n 
            c = (i+1) + (j+1)*n 
            if j%2 == 1: 
                tri += [[a, b, d], [b, c, d]] 
            else: 
                tri += [[a, b, c], [a, c, d]] 
    return np.array(tri, dtype=np.int32) 
 
 
x0 = np.arange(4) * d 
y0 = np.arange(5) * d 
x, y = np.meshgrid(x0, y0) 
x[1::2] -= r 
triangles = meshgrid_triangles(4, 5) 
triangulation = mtri.Triangulation(x.ravel(), y.ravel(), triangles) 
plt.scatter(x, y, color='red') 
plt.triplot(triangulation, 'g-h') 
 
plt.show()