Filled Contour Plots with contourf(X, Y, Z)ΒΆ

Filled contour plots are the colored counterpart to contour line plots: instead of drawing lines at constant values, contourf() fills the regions between contour levels with solid colors from a colormap. Each band of color represents a range of Z values, creating a smooth, map-like visualization of a 2D scalar field.

Why this matters for data science: Filled contours are arguably more intuitive than line contours for most audiences, since the color gradient immediately communicates β€œhigh” versus β€œlow” regions. They are widely used for heatmap-style visualizations of model predictions across a 2D feature space, showing classification probability surfaces, visualizing kernel density estimates, and plotting geospatial data like temperature or precipitation fields. The levels parameter works identically to contour() – here np.linspace(Z.min(), Z.max(), 7) creates seven evenly spaced thresholds. For data science presentations, consider pairing contourf() with contour() to overlay line contours on top of the filled regions for added precision.

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('_mpl-gallery-nogrid')

# make data
X, Y = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2)
levels = np.linspace(Z.min(), Z.max(), 7)

# plot
fig, ax = plt.subplots()

ax.contourf(X, Y, Z, levels=levels)

plt.show()