Home » Tutorial on 3D Contour Plots in Matplotlib

Tutorial on 3D Contour Plots in Matplotlib

Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
1 Year Subscription

3D contour plots are a powerful visualization tool to represent three-dimensional data on a two-dimensional surface. They show contours or “iso-surfaces” that represent different levels of a variable (often a Z value) over a grid of X and Y values.

This is particularly useful in fields like geography, meteorology, and engineering to visualize landscapes, potential fields, or temperature distributions.

In this tutorial, we’ll explore how to create and customize 3D contour plots in Matplotlib using examples covering the basics, filled contours, contour projections, adding color bars, customizing contour levels, and using colormaps.

To create 3D contour plots, we need to import Axes3D from mpl_toolkits.mplot3d and use contour3D or contourf functions to plot the contours.

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

1. Basic 3D Contour Plot

A basic 3D contour plot is created using contour3D, which requires X, Y, and Z coordinates.

# Generate sample 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))

# Create a basic 3D contour plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
contour = ax.contour3D(X, Y, Z, levels=20, cmap='viridis')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("Basic 3D Contour Plot")
plt.show()

In this example:

  • ax.contour3D(X, Y, Z, levels=20, cmap='viridis') creates a 3D contour plot with 20 contour levels and the viridis colormap.
  • The Z values are computed using np.sin(np.sqrt(X**2 + Y**2)), creating concentric contour levels.

2. 3D Contour Plot with Color Bar

A color bar helps interpret the color scale of contour levels, indicating the Z values for each color in the plot.

# 3D contour plot with color bar
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
contour = ax.contour3D(X, Y, Z, levels=20, cmap='plasma')
fig.colorbar(contour, ax=ax, shrink=0.5, aspect=5, label="Z value")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot with Color Bar")
plt.show()

In this example:

  • fig.colorbar(contour, ax=ax, label=”Z value”) adds a color bar on the right side, labeling it with “Z value.”

3. 3D Filled Contour Plot (Isosurface)

Filled contour plots, also called “isosurfaces” in 3D plotting, display continuous color across the contour surface, enhancing readability.

# Generate data for filled contour plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.contourf(X, Y, Z, levels=20, cmap='coolwarm', alpha=0.7)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Filled Contour Plot")
plt.show()

In this example:

  • ax.contourf(X, Y, Z, levels=20, cmap='coolwarm', alpha=0.7) creates a filled contour plot in 3D with a semi-transparent color fill (alpha=0.7).

4. Customizing Contour Levels

You can specify custom contour levels to control where the contours appear on the plot.

# Custom contour levels
custom_levels = [-0.8, -0.4, 0, 0.4, 0.8]

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z, levels=custom_levels, cmap='plasma')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot with Custom Levels")
plt.show()

In this example:

  • levels=custom_levels defines specific contour levels, creating contours only at the specified Z values.

5. 3D Contour Plot with Projections on XY Plane

Contour projections can be added to the XY plane below the 3D plot to show how the contours align with the Z-axis levels on a 2D plane.

# 3D contour plot with projections on the XY plane
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z, levels=20, cmap='viridis')
ax.contour(X, Y, Z, levels=10, cmap='viridis', offset=-1)  # Projected contour on XY plane

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
ax.set_zlim(-1, 1)
plt.title("3D Contour Plot with Projections on XY Plane")
plt.show()

In this example:

  • ax.contour(X, Y, Z, levels=10, offset=-1) adds contours on the XY plane, with offset=-1 setting the Z position of the projected contours.

6. 3D Contour Plot with Different Line Styles and Widths

Customizing line styles and widths can make contours more readable and visually appealing.

# 3D contour plot with custom line styles
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z, levels=10, cmap='cool', linestyles='dashed', linewidths=1.5)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot with Custom Line Styles")
plt.show()

In this example:

  • linestyles='dashed' and linewidths=1.5 customize the contour lines to be dashed and thicker.

7. Logarithmic 3D Contour Plot

For datasets spanning several orders of magnitude, using logarithmic scales for contour levels can help improve readability.

# Logarithmic 3D contour plot
Z_log = np.exp(Z)  # Transform Z values to a larger range for logarithmic plotting

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z_log, levels=np.logspace(0, 3, 10), cmap='inferno')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("Logarithmic 3D Contour Plot")
plt.show()

In this example:

  • np.logspace(0, 3, 10) creates contour levels on a logarithmic scale, making it suitable for large data ranges.

8. Contour Plot Overlayed on a 3D Surface Plot

Overlaying contours on a 3D surface plot combines the continuous surface with contour lines, which can make 3D data easier to interpret.

# Surface plot with overlayed contours
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='coolwarm', alpha=0.6)
ax.contour3D(X, Y, Z, levels=15, cmap='cool', linewidths=1.2)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot with Overlayed Contours")
plt.show()

In this example:

  • ax.plot_surface() creates the surface plot, while ax.contour3D() adds contours on top.
  • alpha=0.6 makes the surface partially transparent, making the contours more visible.

9. Customizing Viewing Angle

Adjusting the viewing angle of the 3D plot can enhance the perspective and make the contour plot easier to interpret.

# Contour plot with custom viewing angle
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.contour3D(X, Y, Z, levels=20, cmap='magma')
ax.view_init(elev=30, azim=45)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot with Custom Viewing Angle")
plt.show()

In this example:

  • ax.view_init(elev=30, azim=45) adjusts the elevation and azimuth angles to improve the view of the plot.

10

. Combining Multiple 3D Contour Sets

You can overlay multiple contour sets on the same plot to compare different levels or highlight specific ranges of data.

# Overlay multiple contour sets
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# First contour set
ax.contour3D(X, Y, Z, levels=10, cmap='Blues', linewidths=1)

# Second contour set with different levels
ax.contour3D(X, Y, Z, levels=[-0.5, 0, 0.5], colors='red', linestyles='solid', linewidths=1.5)

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot with Multiple Contour Sets")
plt.show()

In this example:

  • ax.contour3D(X, Y, Z, levels=[-0.5, 0, 0.5], colors='red') adds a second contour set, highlighting specific levels in red.

11. Projected Contours on Multiple Planes

You can project contours onto multiple planes, such as the XY, YZ, and XZ planes, to show how the data varies along different axes.

# Projected contours on multiple planes
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Surface plot
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none', alpha=0.7)

# Projected contours on XY, YZ, and XZ planes
ax.contour(X, Y, Z, levels=10, cmap='cool', offset=-1, zdir='z')
ax.contour(X, Y, Z, levels=10, cmap='plasma', offset=5, zdir='x')
ax.contour(X, Y, Z, levels=10, cmap='magma', offset=-5, zdir='y')

ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_zlim(-1, 1)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot with Projections on Multiple Planes")
plt.show()

In this example:

  • zdir='z', zdir='x', and zdir='y' specify which plane to project the contours onto.
  • offset defines the position of each projection.

Summary

In this tutorial, we explored a variety of ways to create and customize 3D contour plots in Matplotlib:

  1. Basic 3D Contour Plot to show 3D data contours.
  2. Adding Color Bars for better data interpretation.
  3. 3D Filled Contour Plot for continuous color representation.
  4. Customizing Contour Levels for specific data ranges.
  5. Contour Projections on the XY Plane for data interpretation on 2D.
  6. Custom Line Styles and Widths for visual enhancement.
  7. Logarithmic Contour Plot for data with large ranges.
  8. Overlaying Contours on a Surface Plot for additional depth.
  9. Custom Viewing Angle for better perspective.
  10. Multiple Contour Sets to compare different levels.
  11. Projected Contours on Multiple Planes for 3D data exploration.

These techniques enable you to create insightful 3D contour visualizations, enhancing your ability to explore and present complex three-dimensional data effectively.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More