Skip to content

Matplotlib - 3D Contour Plot

A 3D contour plot is similar to a 2D contour plot but visualized in a three-dimensional space. It shows level curves of a function Z = f(X, Y) drawn at different heights corresponding to the Z value.

To create 3D plots in Matplotlib, you first need to import the mpl_toolkits.mplot3d toolkit, which provides the necessary tools. Then, create an Axes object with a ‘3d’ projection.

The ax.contour3D() function creates the plot. Like its 2D counterpart, it requires input data on a regular 2D grid (X, Y, Z).

import matplotlib.pyplot as plt
import numpy as np
# No need to explicitly import mplot3d toolkit for basic 3D plots
# like contour3D if using plt.axes(projection='3d') or plt.figure().add_subplot(projection='3d')
# from mpl_toolkits import mplot3d # Still good practice for clarity or advanced features
# 1. Define the function to plot
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2)) # Example: Sync function
# 2. Create the data grid
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
# 3. Create a figure and a 3D Axes
fig = plt.figure(figsize=(8, 6))
ax = plt.axes(projection='3d')
# 4. Plot the 3D contour
# Arguments: X, Y, Z data grids
# 50: Number of contour levels
# cmap: Colormap (e.g., 'viridis', 'coolwarm', 'binary')
contour_plot = ax.contour3D(X, Y, Z, 50, cmap='viridis')
# 5. Customize the plot
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis (f(x,y))')
ax.set_title('3D Contour Plot Example')
# Optional: Add a color bar
# fig.colorbar(contour_plot, shrink=0.5, aspect=10, label='f(x,y)')
# Optional: Adjust viewing angle
# ax.view_init(elev=40., azim=-35) # elev = elevation, azim = azimuth
# 6. Show the plot
plt.show()

This code generates a 3D plot showing contour lines of the sync function sin(sqrt(x^2 + y^2)). The contours are drawn at different Z levels, and colored according to the ‘viridis’ colormap, providing a visual representation of the function’s peaks and valleys in 3D space. Axis labels and a title are added for clarity. You can interactively rotate the 3D plot in the Matplotlib window.

  • X, Y, Z: 2D arrays representing the coordinates and the function value.
  • levels (or positional integer): Specifies the number or values of contour levels.
  • cmap: The colormap for coloring the contour lines according to their Z value.
  • colors: Can be used instead of cmap to set a single color or a sequence of colors for the lines.
  • linewidths: Controls the thickness of the contour lines.

You can combine contour3D with other 3D plot types, like plot_surface or scatter3D, on the same Axes for more complex visualizations.