Contour Lines on Unstructured Grids with tricontour(x, y, z)ΒΆ

The tricontour() method draws contour lines through irregularly spaced data points by first computing a Delaunay triangulation and then interpolating the contour curves across the resulting triangular mesh. Unlike contour() which requires data on a regular grid, tricontour() works directly with scattered (x, y, z) point data.

Why this matters for data science: Real-world data collection rarely produces points on a neat rectangular grid. Weather stations, geological surveys, sensor networks, and experimental measurements are typically scattered at irregular locations. tricontour() lets you visualize the spatial structure of such data without the preprocessing step of interpolating onto a regular grid (which can introduce artifacts). The example overlays the raw data points as small grey markers so you can see the irregular sampling pattern alongside the resulting contour lines. The levels=np.linspace(z.min(), z.max(), 7) parameter creates seven evenly spaced contour thresholds. The underlying Delaunay triangulation automatically connects nearby points into triangles, and the contour algorithm traces iso-value curves across this triangular mesh.

import matplotlib.pyplot as plt
import numpy as np

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

# make data:
np.random.seed(1)
x = np.random.uniform(-3, 3, 256)
y = np.random.uniform(-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.plot(x, y, 'o', markersize=2, color='lightgrey')
ax.tricontour(x, y, z, levels=levels)

ax.set(xlim=(-3, 3), ylim=(-3, 3))

plt.show()