Introduction
In this lab, you will learn how to create a triangular 3D filled contour plot using the Matplotlib library in Python. The plot will be created using unstructured triangular grids and customized triangulation. You will be able to control the view angle and color map of the plot.
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.
Import Libraries
The first step is to import the necessary libraries. In this case, we will need Matplotlib, Numpy, and Matplotlib Tri.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.tri as tri
Create the Coordinates
Next, we will create the x, y, z coordinates of the points. We will create the mesh in polar coordinates and compute x, y, z.
n_angles = 48
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
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(3*angles)).flatten()
Create a Custom Triangulation
In this step, we will create a custom triangulation and mask off unwanted triangles.
triang = tri.Triangulation(x, y)
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
Create the Plot
Now, we will create the plot using the tricontourf() function and customize the view angle.
ax = plt.figure().add_subplot(projection='3d')
ax.tricontourf(triang, z, cmap=plt.cm.CMRmap)
ax.view_init(elev=45.)
plt.show()
Summary
In this lab, you learned how to create a triangular 3D filled contour plot using Matplotlib in Python. You learned how to create the coordinates, create a custom triangulation, and customize the view angle and color map of the plot.