Contour Line Plots with contour(X, Y, Z)ΒΆ

Contour plots draw lines of constant value (isolines) across a 2D scalar field, much like elevation lines on a topographic map. The Axes.contour() method takes 2D arrays X, Y, and Z and draws curves where Z equals specific threshold values, controlled by the levels parameter.

Why this matters for data science: Contour plots are one of the most important visualization tools in machine learning for understanding optimization landscapes. They are used to plot decision boundaries of classifiers, visualize loss functions over two parameters, display 2D probability density functions, and show response surfaces from experiments. The levels parameter, set here using np.linspace() between the min and max of Z, determines how many contour lines are drawn and at what values. Fewer levels give a cleaner overview; more levels reveal finer detail in the surface. The mathematical function used here – a polynomial multiplied by a Gaussian decay – produces an asymmetric surface with interesting features like saddle points, which makes it a good test case for contour visualization.

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(np.min(Z), np.max(Z), 7)

# plot
fig, ax = plt.subplots()

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

plt.show()