Matplotlib - 3D Contours



3D contours refer to the lines or curves that show the shape and height of objects in a three-dimensional space. These contours help us understand how high or low different parts of an object are. They are commonly used in fields like geography, engineering, and art to represent the shape of things in a more detailed way.

For example, if you have a mountain, its 3D contours will show the slopes, valleys, and peaks from all sides. Similarly, if you have a sculpture of an animal, its 3D contours will describe the shape of its body, head, and limbs from various viewpoints −

3D Contours

3D Contours in Matplotlib

In Matplotlib, 3D contours represent the surface of a three-dimensional object. It allows you to create 3D contour plots by providing your data points representing the x, y, and z coordinates. These points define the shape of the object you want to visualize. Then, Matplotlib can generate contour lines or surfaces to represent the contours of your 3D data.

You can create 3d contours in Matplotlib using the contour3D() function in the "mpl_toolkits.mplot3d" module. This function accepts the three coordinates - X, Y, and Z as arrays and plots a line across the X and Y coordinate to show the outline or change in height of a 3D object along the z-axis.

Let's start by drawing a basic 3D contour.

Basic 3D Contour

A basic 3D contour in Matplotlib is like drawing elevation lines on a map but in three dimensions. It uses X, Y, and Z axes to show the changes in height of a surface across different points.

Example

In the following example, we are creating a basic 3D contour by first plotting the X and Y coordinates. Then, we take the sum of sine and cosine values of X and Y to get the change in elevation. The resultant plot displays the outline of the shape with different heights on Z axis −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Creating data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D contour
ax.contour3D(X, Y, Z, 50, cmap='viridis')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Basic 3D Contour Plot')

# Displaying the plot
plt.show()

Output

Following is the output of the above code −

Basic 3D Contour

Parametric 3D Contours

Parametric 3D contours in Matplotlib represent outline of shapes at different heights using mathematical parameters in three dimensions. The contours are not only defined by the changes in X, Y, and Z coordinates but also by changes in the parameters.

Example

In here, we are parameterizing the X, Y, and Z coordinates based on the the size (R), thickeness (r) and initial coordinates (u, v) of the 3D object. The resultant plot creates a donut-shaped 3D contour −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Parametric equations for a torus
def torus_parametric(u, v, R=1, r=0.3):
   x = (R + r * np.cos(v)) * np.cos(u)
   y = (R + r * np.cos(v)) * np.sin(u)
   z = r * np.sin(v)
   return x, y, z

# Creating data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, 2 * np.pi, 100)
U, V = np.meshgrid(u, v)
X, Y, Z = torus_parametric(U, V)

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the parametric 3D contour
ax.contour3D(X, Y, Z, 50, cmap='plasma')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('Parametric 3D Contour Plot (Torus)')

# Displaying the plot
plt.show()

Output

On executing the above code we will get the following output −

Parametric 3D Contours

3D Contours from Irregular Data

In Matplotlib, 3D contours from irregular data show the outline of a 3D surface whose data points are random. In this type of contour, we calculate the missing data points by estimating the values based on the X, Y, and Z values.

Example

The following example creates a 3D contour from irregular data. Here, we calculate the missing data points and interpolate them linearly with known data points. This creates a smooth and continuous 3D contour as the result −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from scipy.interpolate import griddata

# Creating irregularly spaced data
np.random.seed(42)
x = np.random.rand(100)
y = np.random.rand(100)
z = np.sin(x * y)

# Creating a regular grid
xi, yi = np.linspace(x.min(), x.max(), 100), np.linspace(y.min(), y.max(), 100)
xi, yi = np.meshgrid(xi, yi)

# Combining irregular data onto the regular grid
zi = griddata((x, y), z, (xi, yi), method='linear')

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D contour from irregular data on the regular grid
ax.contour3D(xi, yi, zi, 50, cmap='viridis')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Contour Plot from Irregular Data')

# Displaying the plot
plt.show()

Output

After executing the above code, we get the following output −

3D Contours from Irregular Data

Contour Lines in 3D Contours

In Matplotlib, contour lines in 3D contours visually represents the 3D contour of an object along with its contour lines in three dimensions. The contour lines represent the slope of a 3D contour and are represented in the XY plane as they do not have any Z value (no depth). The function "contour()" is used to show the contour lines of an object.

Example

Now, we are creating a 3D contour and contour lines of an object. We plot a 3D contour on the z-axis and the contour lines on the XY plane. The resultant plot shows the outline of the object on the z-axis along with its slope on XY plane −

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Creating data
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting the 3D contour
ax.contour3D(X, Y, Z, 50, cmap='plasma')

# Adding contour lines on the XY plane
ax.contour(X, Y, Z, zdir='z', offset=np.min(Z), cmap='plasma')

# Customizing the plot
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('3D Contour Plot with Contour Lines')

# Displaying the plot
plt.show()

Output

On executing the above code we will get the following output −

Contour Lines in 3D Contours
Advertisements