Matplotlib - Contour Plot
Matplotlib - Contour Plots
Section titled “Matplotlib - Contour Plots”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.
Creating the Data Grid
Section titled “Creating the Data Grid”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 vectorsx_coords = np.linspace(-3.0, 3.0, 50)y_coords = np.linspace(-3.0, 3.0, 50)
# Create the 2D gridX, Y = np.meshgrid(x_coords, y_coords)
# Define the function Z = f(X, Y)# Example: Z represents distance from the originZ = np.sqrt(X**2 + Y**2)Plotting Contours
Section titled “Plotting Contours”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.
Example: Filled Contour Plot
Section titled “Example: Filled Contour Plot”import numpy as npimport matplotlib.pyplot as plt
# 1. Create data gridxlist = 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 functionZ = np.sin(np.sqrt(X**2 + Y**2)) + np.cos(X * Y)
# 3. Create Figure and Axesfig, 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 valuescp = 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 scalecbar = fig.colorbar(cp)cbar.set_label('Z value')# cbar.add_lines(line_cp) # Optionally add lines to colorbar
# 7. Add labels and titleax.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.
Key Parameters:
Section titled “Key Parameters:”levels: Controls the number and position of contour levels.cmap: Specifies the colormap used forcontourf.colors: Specifies the color(s) for lines incontour.linewidths: Specifies the thickness of lines incontour.