Draw a unstructured triangular grid as lines or markers in Python using Matplotlib - GeeksforGeeks

08 Jun, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
An unstructured grid can be defined as the part of the Euclidean plane or diagram that can be fit together in a pattern with no spaces in between two shapes.  Unstructured grid can be  triangle or tetrahedra in an irregular pattern. Unstructured Triangular Grid can be drawn from an irregularly shaped polygon using the Ruppert’s algorithm.
Here the task is to draw a unstructured triangular grid as lines and/or markers in Python using Matplotlib. In order to do this task, you can use the triplot() function and we require some modules from matplotlib and numpy library.
Example 1: Creating and plotting unstructured triangular grids.
Python3
# Importing modulesimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np    n_angles = 24n_radii = 9min_radius = 0.5radii = np.linspace(min_radius, 0.9,                    n_radii)  angles = np.linspace(0, 6 * np.pi, n_angles,                     endpoint=False)  angles = np.repeat(angles[..., np.newaxis],                   n_radii, axis=1)  angles[:, 1::2] += np.pi / n_angles  x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()triang = tri.Triangulation(x, y)  triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),                         y[triang.triangles].mean(axis=1))                < min_radius)  plt.triplot(triang, 'o-', lw=1)plt.title('Example 1')plt.show()
Output:
Example 2: Using the TriFinder object to highlight the unstructured triangular grid.
Python3
# Importing modules import matplotlib.pyplot as pltfrom matplotlib.tri import Triangulationfrom matplotlib.patches import Polygonimport numpy as np    def Trigolo1(tri):        if tri == -1:        points = [0, 0, 0]              else:        points = triang.triangles[tri]              xs = triang.x[points]    ys = triang.y[points]    polygon.set_xy(np.column_stack([xs, ys]))  def Trigolo2(event):        if event.inaxes is None:        tri = -1              else:        tri = trifinder(event.xdata, event.ydata)              Trigolo1(tri)    plt.title('Example 2\nTriangle No : %i' % tri)    event.canvas.draw()  # Create a Triangulation.ang = 16rad = 5mrad = 0.25radii = np.linspace(mrad, 0.95, rad)  angletri = np.linspace(0,                       2 * np.pi, ang,                        endpoint=False)  angletri = np.repeat(angletri[..., np.newaxis],                      rad,                     axis=1)  angletri[:, 1::2] += np.pi / ang  x = (radii*np.cos(angletri)).flatten()y = (radii*np.sin(angletri)).flatten()  triang = Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),                         y[triang.triangles].mean(axis=1))                < mrad)  # Use the triangulation's default TriFinder object.trifinder = triang.get_trifinder()  # Setup plot and callbacks.plt.subplot(111, aspect='equal')plt.triplot(triang, 'o-')polygon = Polygon([[0, 0], [0, 0]], facecolor='y')Trigolo1(-1)plt.gca().add_patch(polygon)plt.gcf().canvas.mpl_connect('motion_notify_event', Trigolo2)  plt.show()
Output:
Example 3: Example showing the plot the triangulation.
Python3
import matplotlib.pyplot as plt import matplotlib.tri as mtri import numpy as np        # Create triangulation. x = np.asarray([0, 1, 2,                 3, 0.5, 1.5,                 2.5, 1, 2,                1.5])     y = np.asarray([0, 0, 0,                 0, 1.0, 1.0,                1.0, 2, 2,                3.0])     triangles = [[0, 1, 4], [1, 2, 5],               [2, 3, 6], [1, 5, 4],               [2, 6, 5], [4, 5, 7],              [5, 6, 8], [5, 8, 7],              [7, 8, 9]]     triang = mtri.Triangulation(x, y, triangles) z = np.cos(1.5 * x) * np.cos(1.5 * y)      plt.tricontourf(triang, z) plt.triplot(triang, 'go-')      plt.title('Example 3')   plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python