More Triangular 3D Surfaces

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

This tutorial demonstrates how to create 3D surfaces using triangular mesh in Python's Matplotlib library. It shows two examples of plotting surfaces with triangular mesh.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} matplotlib/figures_axes -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} python/booleans -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} python/lists -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} python/tuples -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} python/importing_modules -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} python/numerical_computing -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} python/data_visualization -.-> lab-49012{{"`More Triangular 3D Surfaces`"}} end

Import Required Libraries

We begin by importing the required libraries: matplotlib.pyplot and numpy. We also import matplotlib.tri to create the triangular meshes.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.tri as mtri

Create a Mesh

We create a mesh in the space of parameterization variables u and v. This is done using the np.meshgrid() function to create a grid of u and v points.

u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50)
v = np.linspace(-0.5, 0.5, endpoint=True, num=10)
u, v = np.meshgrid(u, v)
u, v = u.flatten(), v.flatten()

Define the Surface

Next, we define the surface. In this example, we use a Mobius mapping to take a u, v pair and return an x, y, z triple.

x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u)
y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u)
z = 0.5 * v * np.sin(u / 2.0)

Triangulate Parameter Space

We triangulate the parameter space to determine the triangles that will connect the x, y, z points.

tri = mtri.Triangulation(u, v)

Plot the Surface

Finally, we plot the surface using plot_trisurf() function. The triangles in parameter space determine which x, y, z points are connected by an edge.

ax = plt.figure().add_subplot(projection='3d')
ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=plt.cm.Spectral)
ax.set_zlim(-1, 1)

Create a Mask

In this example, we create a mask to remove unwanted triangles. We first create parameter spaces radii and angles.

n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)

angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles

Map to x, y, z Points

We map the radius, angle pairs to x, y, z points.

x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(3*angles)).flatten()

Create Triangulation

We create the triangulation using the Triangulation() function. Since there are no triangles, the Delaunay triangulation is created.

triang = mtri.Triangulation(x, y)

Mask Off Unwanted Triangles

We mask off unwanted triangles by calculating the midpoint of each triangle and checking if it falls within a given radius.

xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = xmid**2 + ymid**2 < min_radius**2
triang.set_mask(mask)

Plot the Surface

Finally, we plot the surface using plot_trisurf() function.

ax = plt.figure().add_subplot(projection='3d')
ax.plot_trisurf(triang, z, cmap=plt.cm.CMRmap)

Summary

This tutorial demonstrated how to create 3D surfaces using triangular mesh in Python's Matplotlib library. We covered the steps involved in creating a mesh, defining the surface, triangulating parameter space, creating a mask, and plotting the surface.

Other Python Tutorials you may like