TExcelTAD
Home › Matplotlib › Contour Plots

Contour Plots

A contour plot shows a 3-D surface on a flat page using lines of equal height, exactly like the contour lines on a hiking map. Each line connects points where the function has the same value. Matplotlib draws contour lines with contour() and filled bands with contourf().

Building the grid

Contour functions need the function's value at every point of a grid. np.meshgrid turns two 1-D coordinate arrays into 2-D grids:

python · try it yourself
import numpy as np

x = np.array([0, 1, 2])
y = np.array([10, 20])
X, Y = np.meshgrid(x, y)

print("X =")
print(X)
print("Y =")
print(Y)
print("X + Y =")
print(X + Y)
X =
[[0 1 2]
 [0 1 2]]
Y =
[[10 10 10]
 [20 20 20]]
X + Y =
[[10 11 12]
 [20 21 22]]

Every position [i, j] pairs X[i, j] with Y[i, j], so any NumPy expression of X and Y computes the function on the whole grid at once.

Contour lines

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = np.exp(-(X - 1) ** 2 - Y ** 2) + 0.7 * np.exp(-(X + 1.2) ** 2 - (Y - 1) ** 2)

fig, ax = plt.subplots(figsize=(5.5, 5))
cs = ax.contour(X, Y, Z, levels=8, cmap="viridis")
ax.clabel(cs, fontsize=8)                  # write the value on each line
ax.set_aspect("equal")
ax.set_title("Two hills")
plt.show()

print("Contour levels:", np.round(cs.levels, 3).tolist())
Contour levels: [0.0, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.05]

levels=8 asks for about 8 "nice" levels; you can also pass the exact values, e.g. levels=[0.2, 0.5, 0.8]. ax.clabel() writes the level value on the lines.

Filled contours

contourf() fills the bands between levels. It reads like a heatmap with a fixed number of colours, and it combines well with a colorbar and a few thin lines on top:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = np.exp(-(X - 1) ** 2 - Y ** 2) + 0.7 * np.exp(-(X + 1.2) ** 2 - (Y - 1) ** 2)

levels = np.linspace(0, 1.1, 12)
fig, ax = plt.subplots(figsize=(6, 5))
filled = ax.contourf(X, Y, Z, levels=levels, cmap="terrain")
ax.contour(X, Y, Z, levels=levels, colors="black", linewidths=0.4)
fig.colorbar(filled, ax=ax, label="height")
ax.set_aspect("equal")
plt.show()

peak = np.unravel_index(Z.argmax(), Z.shape)
print(f"Highest point: z = {Z.max():.3f} at x = {X[peak]:.2f}, y = {Y[peak]:.2f}")
Highest point: z = 1.002 at x = 1.01, y = 0.02

Diverging data and negative contours

When a function takes positive and negative values, use a diverging colormap centred on zero. By default, contour draws negative levels as dashed lines when you use a single colour:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2 * np.pi, 2 * np.pi, 300)
y = np.linspace(-np.pi, np.pi, 150)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)

fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
ax.contourf(X, Y, Z, levels=np.linspace(-1, 1, 11), cmap="RdBu_r")
lines = ax.contour(X, Y, Z, levels=[-0.5, 0, 0.5], colors="k", linewidths=1)
ax.clabel(lines, fontsize=8)
ax.set_title(r"$z = \sin x \cos y$ (negative levels dashed)")
plt.show()

print("Line levels:", lines.levels.tolist())
print("Negative levels drawn as:", plt.rcParams["contour.negative_linestyle"])
Line levels: [-0.5, 0.0, 0.5]
Negative levels drawn as: dashed

A practical example: a cost landscape

Contours are common in optimisation and machine learning to show a "loss landscape". Here we draw the contours of a bowl-shaped function and the path of a few gradient-descent steps on top:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
    return (x - 1) ** 2 + 4 * (y + 0.5) ** 2

def grad(x, y):
    return np.array([2 * (x - 1), 8 * (y + 0.5)])

X, Y = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-2, 1.5, 200))

point = np.array([-2.5, 1.2])
path = [point]
for _ in range(12):
    point = point - 0.1 * grad(*point)
    path.append(point)
path = np.array(path)

fig, ax = plt.subplots(figsize=(7, 4.5))
cs = ax.contour(X, Y, f(X, Y), levels=[0.25, 1, 2, 4, 8, 16, 32], cmap="Blues_r")
ax.clabel(cs, fontsize=8)
ax.plot(path[:, 0], path[:, 1], "o-", color="C3", ms=4, label="gradient descent")
ax.plot(1, -0.5, "k*", ms=12, label="minimum")
ax.legend(loc="upper right")
plt.show()

print(f"Start f = {f(*path[0]):.2f}, after 12 steps f = {f(*path[-1]):.4f}")
Start f = 23.81, after 12 steps f = 0.0578
Function Draws
contour(X, Y, Z, levels) lines of equal value
contourf(X, Y, Z, levels) filled bands between levels
clabel(cs) value labels on contour lines
tricontour(x, y, z) contours from scattered (non-grid) points

Test yourself

What does a single contour line connect?

  1. Points with the same x
  2. Points where the function has the same value
  3. The highest points
  4. Random points

What is the difference between contour and contourf?

  1. contourf is faster
  2. contourf fills the bands between levels
  3. contour needs a meshgrid, contourf doesn't
  4. There is no difference

What does np.meshgrid(x, y) produce for x of length 3 and y of length 2?

  1. Two arrays of shape (3, 2)
  2. Two arrays of shape (2, 3)
  3. One array of length 6
  4. A 3-D array