Skip to content

Matplotlib - Contour Plot

Contour plots (or level plots) visualize a three-dimensional surface on a two-dimensional plane. They display lines (contours) connecting points of equal value (e.g., altitude, temperature, pressure) from a 3D function Z = f(X, Y). Filled contour plots use colored regions between contours to represent the Z value.

Contour plots are ideal when you want to understand how a response variable Z changes as a function of two predictor variables X and Y.

Contour plots typically require data evaluated on a regular grid. The numpy.meshgrid function is essential for this. It takes arrays of X and Y coordinates and creates coordinate matrices representing all combinations of X and Y values in the grid.

import numpy as np
# Define the x and y coordinate vectors
x_coords = np.linspace(-3.0, 3.0, 50)
y_coords = np.linspace(-3.0, 3.0, 50)
# Create the 2D grid
X, Y = np.meshgrid(x_coords, y_coords)
# Define the function Z = f(X, Y)
# Example: Z represents distance from the origin
Z = np.sqrt(X**2 + Y**2)

Matplotlib provides two main functions for contour plots within the Axes object:

  • ax.contour(X, Y, Z, levels, ...): Draws contour lines.
  • ax.contourf(X, Y, Z, levels, ...): Creates filled contours.

Both functions take the grid coordinates X, Y, and the corresponding values Z as primary inputs. You can optionally specify the number of contour levels or the specific values at which to draw contours.

import numpy as np
import matplotlib.pyplot as plt
# 1. Create data grid
xlist = np.linspace(-3.0, 3.0, 100)
ylist = np.linspace(-3.0, 3.0, 100)
X, Y = np.meshgrid(xlist, ylist)
# 2. Define function Z = f(X, Y) - Example: A wavy function
Z = np.sin(np.sqrt(X**2 + Y**2)) + np.cos(X * Y)
# 3. Create Figure and Axes
fig, ax = plt.subplots(figsize=(7, 6))
# 4. Create the filled contour plot
# cmap specifies the colormap (e.g., 'viridis', 'plasma', 'coolwarm')
# levels can be an integer (number of levels) or a list of contour values
cp = ax.contourf(X, Y, Z, levels=15, cmap='viridis')
# 5. Add contour lines for clarity (optional)
line_cp = ax.contour(X, Y, Z, levels=cp.levels, colors='black', linewidths=0.5)
# 6. Add a color bar to show the Z value scale
cbar = fig.colorbar(cp)
cbar.set_label('Z value')
# cbar.add_lines(line_cp) # Optionally add lines to colorbar
# 7. Add labels and title
ax.set_title('Filled Contour Plot Example')
ax.set_xlabel('X coordinate')
ax.set_ylabel('Y coordinate')
# 8. Ensure aspect ratio is equal if needed (optional)
# ax.set_aspect('equal', adjustable='box')
plt.show()

This code generates a filled contour plot. It first creates a 2D grid using meshgrid, calculates the Z value for each point on the grid, then uses ax.contourf to draw the filled contours with the ‘viridis’ colormap. Optional contour lines are added using ax.contour, and a color bar is included to map colors to Z values. Titles and labels make the plot understandable.

  • levels: Controls the number and position of contour levels.
  • cmap: Specifies the colormap used for contourf.
  • colors: Specifies the color(s) for lines in contour.
  • linewidths: Specifies the thickness of lines in contour.