Search code examples
pythonmatplotlib2dpolygontriangulation

Triangulation of a polygon using matplotlib


I've tried to use the matplot.Delaunay for the triangulation of a simple polygon in 2D... The problem here is that I need regular triangles. The polygon is randomly created by numpy, maybe Delaunay it's not the way to go.

import matplotlib.delaunay as triang
import pylab
import numpy

# 10 random points (x,y) in the plane
x,y =  numpy.array(numpy.random.standard_normal((2,10)))
cens,edg,tri,neig = triang.delaunay(x,y)

for t in tri:
 # t[0], t[1], t[2] are the points indexes of the triangle
 t_i = [t[0], t[1], t[2], t[0]]
 pylab.plot(x[t_i],y[t_i])


pylab.plot(x,y,'^')
pylab.show()

Solution

  • I guess, triangulation by regular triangles is not a trivial task for a random polygon. However if you want to use only regular triangles, you have to define points' coordinate manually. Like in this example:

    import matplotlib.pyplot as plt
    import matplotlib.tri as tri
    import numpy as np
    import math
    
    # Creating a Triangulation without specifying the triangles results in the
    # Delaunay triangulation of the points.
    
    # First create the x and y coordinates of the points.
    n_angles = 36
    n_radii = 8
    min_radius = 0.25
    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 Triangulation; no triangles so Delaunay triangulation created.
    triang = tri.Triangulation(x, y)
    
    # Mask off unwanted triangles.
    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
    triang.set_mask(mask)
    
    # Plot the triangulation.
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, 'bo-')
    plt.title('triplot of Delaunay triangulation')
    
    plt.show()
    

    enter image description here