Matplotlib Contour Plots with contour and contourf

Draw contour lines and filled contour plots in Matplotlib, choose levels, label the lines, mark zero, and contour scattered data.

To make a contour plot in Matplotlib, call ax.contourf(X, Y, Z) for filled bands or ax.contour(X, Y, Z) for lines. Z is a 2D array of heights, and X and Y give the coordinates of its columns and rows. Pass levels to control where the boundaries fall.

Quick Example

This draws filled pressure bands, outlines them, and labels the lines.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1000, 201)
y = np.linspace(0, 700, 141)
X, Y = np.meshgrid(x, y)


def bump(cx, cy, sx, sy):
    return np.exp(-(((X - cx) / sx) ** 2 + ((Y - cy) / sy) ** 2))


pressure = 1013 + 17 * bump(260, 450, 230, 190) - 22 * bump(720, 250, 210, 170)

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
filled = ax.contourf(X, Y, pressure, levels=np.arange(988, 1033, 4), cmap="RdYlBu_r")
lines = ax.contour(X, Y, pressure, levels=filled.levels, colors="black", linewidths=0.7)
ax.clabel(lines, fontsize=8)
fig.colorbar(filled, ax=ax, label="Pressure (hPa)")
ax.set_title("Sea-level pressure with a high and a low")
ax.set_xlabel("East (km)")
ax.set_ylabel("North (km)")
ax.set_aspect("equal")
plt.show()

Matplotlib filled contour map with labeled black contour lines showing a red high pressure area in the upper left and a blue low in the lower right

The high peaks just under 1030 hPa in the upper left, and the low bottoms out near 991 hPa in the lower right. The code targets Matplotlib 3.10 and 3.11.

What Shape Should X, Y, and Z Be?

Z must be 2D, with shape (rows, columns). X and Y can take either form:

  • 1D arrays, with len(x) equal to the number of columns and len(y) equal to the number of rows.
  • 2D arrays the same shape as Z, usually from np.meshgrid(x, y). These are handy when you compute Z from a formula.

Here x has 201 values and y has 141, so Z has shape (141, 201). If your array is the other way around, you get an error such as Length of x (5) must match number of columns in z (3), and passing Z.T fixes it.

A table in long format (one row per x, y, value) needs to be pivoted into a grid first, for example with df.pivot(index="y", columns="x", values="z").

contour vs contourf

contour draws lines along each level. contourf fills the space between levels. Drawing both, with the same levels, gives crisp edges between the bands.

fig, axes = plt.subplots(1, 3, figsize=(11, 3), sharey=True, layout="constrained")
axes[0].contour(X, Y, pressure)
axes[0].set_title("contour: lines")
axes[1].contourf(X, Y, pressure)
axes[1].set_title("contourf: filled bands")
cf = axes[2].contourf(X, Y, pressure)
axes[2].contour(X, Y, pressure, levels=cf.levels, colors="white", linewidths=0.8)
axes[2].set_title("both")
for ax in axes:
    ax.set_aspect("equal")
plt.show()

Three Matplotlib panels comparing contour lines, filled contourf bands, and filled bands with white outlines

You want to... Use
Show overall shape and magnitude contourf with a colorbar
Read exact values off the chart contour with clabel
Lay contours over a map, image, or scatter plot contour, so the layer underneath stays visible
Show every cell of coarse gridded data imshow or pcolormesh, as in Matplotlib heatmaps

Setting Contour Levels

levels takes an integer or a list of values. An integer is a target, not an exact count: Matplotlib picks round numbers, and levels=4 below produces six bands. A list sets the boundaries exactly and must be increasing.

fig, axes = plt.subplots(1, 3, figsize=(12, 3.2), sharey=True, layout="constrained")
settings = [
    ("levels=4", {"levels": 4}),
    ("levels=20", {"levels": 20}),
    ('explicit levels, extend="both"', {"levels": [1000, 1008, 1012, 1016, 1024], "extend": "both"}),
]
for ax, (title, kwargs) in zip(axes, settings):
    cf = ax.contourf(X, Y, pressure, cmap="viridis", **kwargs)
    fig.colorbar(cf, ax=ax, shrink=0.8)
    ax.set_title(title)
    ax.set_aspect("equal")
plt.show()

Matplotlib filled contour plots with 4 levels, 20 levels, and uneven explicit levels with pointed colorbar ends

With explicit levels, contourf leaves anything below the first or above the last value blank. If you see an unexpected white hole at a peak or trough, widen the list or add extend="both" (or "min", "max"), which colors the out-of-range areas and adds arrows to the colorbar. See customizing a Matplotlib colorbar for its ticks, size, and position.

Labeling Contour Lines with clabel

ax.clabel() writes each level's value into a gap in its line. fmt accepts a format string, a function, or a dict mapping levels to text. Unevenly spaced levels help when the values change quickly in one region and slowly in another.

u = np.linspace(-3, 3, 200)
U, V = np.meshgrid(u, u)
loss = np.log1p((1 - U) ** 2 + 4 * (V - 0.35 * U**2) ** 2)

fig, ax = plt.subplots(figsize=(7, 5), layout="constrained")
levels = [0.25, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4]
cs = ax.contour(U, V, loss, levels=levels, cmap="plasma", linewidths=1.8)
ax.clabel(cs, fmt="%.2g", fontsize=9)
best = np.unravel_index(loss.argmin(), loss.shape)
ax.plot(U[best], V[best], "*", color="black", markersize=14, linestyle="none", label="Minimum")
ax.legend(loc="lower right")
ax.set_title("A curved loss surface")
ax.set_xlabel("Parameter a")
ax.set_ylabel("Parameter b")
plt.show()

Matplotlib contour lines labeled with their values around a curved valley with a black star at the minimum

To label only some lines, pass them as the second argument, such as ax.clabel(cs, [0.5, 2, 4]).

Negative Values and the Zero Line

When contour uses a single color, negative levels are drawn dashed by default (negative_linestyles="solid" turns that off). For data centered on zero, use a diverging colormap, make the levels symmetric so zero lands on the color change, and draw the zero contour again with a heavier line.

change = 6 * bump(300, 220, 240, 200) - 3.5 * bump(760, 480, 200, 180)
levels = np.linspace(-6, 6, 13)

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
cf = ax.contourf(X, Y, change, levels=levels, cmap="BrBG")
ax.contour(X, Y, change, levels=levels[levels != 0], colors="#333333", linewidths=0.6)
ax.contour(X, Y, change, levels=[0], colors="black", linewidths=2.5)
fig.colorbar(cf, ax=ax, label="Soil moisture change (points)", ticks=levels[::2])
ax.set_title("Dashed lines are negative, the heavy line is zero")
ax.set_aspect("equal")
plt.show()

Matplotlib diverging contour plot with green positive bands, brown negative bands with dashed outlines, and a thick black zero line

The same levels=[value] pattern highlights any threshold, such as a safety limit or a classifier's decision boundary.

Contour Plots from Scattered Data

If your measurements aren't on a grid, ax.tricontourf(x, y, z) takes three 1D arrays. It triangulates the points and interpolates linearly across each triangle.

rng = np.random.default_rng(58)
px = rng.uniform(0, 1000, 180)
py = rng.uniform(0, 700, 180)
depth = 20 + 0.045 * px + 18 * np.exp(-(((px - 420) / 200) ** 2 + ((py - 380) / 160) ** 2))
depth += rng.normal(0, 0.8, px.size)

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
cf = ax.tricontourf(px, py, depth, levels=12, cmap="Blues")
ax.tricontour(px, py, depth, levels=cf.levels, colors="#0f172a", linewidths=0.5)
ax.plot(px, py, ".", color="#dc2626", markersize=5)
fig.colorbar(cf, ax=ax, label="Depth (m)")
ax.set_title("Depth contours from 180 soundings (red dots)")
ax.set_aspect("equal")
plt.show()

Matplotlib tricontourf depth map in shades of blue with red dots at the scattered measurement points

The jagged lines come from the linear interpolation and measurement noise, and the blank slivers at the edges lie outside the outermost points. For smoother contours, interpolate onto a grid first (for example with scipy.interpolate.griddata) and call contourf.

Practical Tips

  • Use ax.set_aspect("equal") when x and y share units, so circles stay circular.
  • NaN and masked values in Z are left blank.
  • Around 8 to 12 levels is usually readable. Many more starts to look like a continuous color map, which pcolormesh draws more directly.
  • To view the same surface in three dimensions, see 3D plots in Matplotlib, which also projects contours onto the floor of the plot.

Similar Topics