Let's explore how to create 3D contour plots in Python using Matplotlib.
These plots are
excellent for visualizing 3D surfaces defined by a function of two variables.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm # For colormaps
# 1. Define the function (surface)
def f(x, y):
return np.sin(np.sqrt(x**2 + y**2)) # Example: A cone-like
surface
# 2. Create the meshgrid (x and y values)
x = np.linspace(-5, 5, 100) # Adjust range and density as needed
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y) # Creates the grid
# 3. Calculate the Z values (heights)
Z = f(X, Y)
# 4. Create the figure and axes
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
# 5. Create the contour plot
# There are two ways to create a contour plot:
# a) Filled contours:
# contour = ax.contourf(X, Y, Z, levels=20, cmap=cm.viridis) # levels
controls how many contours are shown
# fig.colorbar(contour, shrink=0.75, pad=0.1) # Add a colorbar
# b) Line contours:
contour = ax.contour(X, Y, Z, levels=20, cmap=cm.coolwarm)
# ax.clabel(contour, inline=True, fontsize=8) # Add labels to the
contour lines
# You can use both contourf and contour together if you want
# 6. Set labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Contour Plot')
# 7. Customize (Optional)
# ax.view_init(elev=30, azim=45) # Adjust viewing angle
# ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.5)) #Set the color of
the z-axis plane
# 8. Show the plot
plt.show()
Explanation and Key Improvements:
1. Function Definition: The f(x, y) function defines the surface you want to plot. Change
this function to explore different surfaces.
2. np.meshgrid(): This is essential. It creates the X and Y grids needed for the contour plot.
X and Y are 2D arrays.
3. ax.contourf() (Filled Contours) or ax.contour() (Line Contours): These are the core
functions.
○ levels: Controls the number and spacing of contour lines. You can provide a list of
specific levels or an integer for automatic level selection.
○ cmap: Sets the colormap (e.g., cm.viridis, cm.plasma, cm.coolwarm, cm.jet).
Explore Matplotlib's colormap options.
4. fig.colorbar(): Adds a colorbar to the plot for filled contours, which is extremely helpful for
interpreting the Z values.
5. ax.clabel(): Adds labels to the contour lines for line contours.
6. Customization:
○ ax.view_init(elev, azim): Adjusts the viewing angle. elev is the elevation angle, and
azim is the azimuthal angle.
○ ax.w_zaxis.set_pane_color(): Change the color of the background planes.
7. Colormaps: Colormaps are important for visualizing the height information effectively.
Matplotlib has a wide variety of colormaps. You can even create your own.
Example with a different function:
def f(x, y):
return x**2 - y**2 # Saddle-like surface
Just change the f(x, y) function, and the rest of the code will work to generate the contour plot
for the new surface. Experiment with different functions and colormaps to get a feel for how they
affect the visualization.