将NumPy 2D阵列中的所有2D点连接为三角形网格 [英] Connect all 2D Points from NumPy 2D Arrays as a triangular meshgrid
本文介绍了将NumPy 2D阵列中的所有2D点连接为三角形网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对Python来说还很陌生,我正试图绘制一个像这样的三角形网格:
I am pretty new to Python and I am trying to plot a triangular grid like this:
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))
的水平线,但是我不知道如何绘制垂直"之字形线...有人有简单"的解决方案吗?
My problem is, that I have no real clue how to connect all points. I have added horizontal lines with plt.plot(*zip(*l1))
for all l
but I have no idea how to draw the 'vertical' zigzag lines... Has anybody a 'simple' solution?
非常感谢!
推荐答案
triplot is made for that purpose: plotting triangles.
You can either pass only x
and y
coordinates (in this case a Delaunay triangulation will be computed), or a full Triangulation
object to which you can specify your own triangles.
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()
这篇关于将NumPy 2D阵列中的所有2D点连接为三角形网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文