Streamline Plots with streamplot(X, Y, U, V)ΒΆ
A streamline plot traces continuous curves that are everywhere tangent to a vector field, showing the flow paths that a particle would follow through the field. Unlike quiver plots which show discrete arrows at grid points, streamplot() creates smooth, flowing lines that reveal the global structure of the vector field.
Why this matters for data science: Streamlines provide a more intuitive view of flow patterns than quiver plots, especially for identifying features like vortices, sources, sinks, and saddle points. They are used in fluid dynamics visualization, electromagnetic field analysis, and for understanding the dynamics of differential equations. In ML, streamlines can visualize the flow of a gradient field, showing how different initializations of gradient descent would converge (or diverge). The example derives U and V from the numerical gradient of a stream function using np.diff(), which is a standard technique in fluid mechanics. The negative sign on U ensures the velocity field is divergence-free (incompressible), meaning the streamlines form closed loops rather than emanating from sources.
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery-nogrid')
# make a stream function:
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)
# make U and V out of the streamfunction:
V = np.diff(Z[1:, :], axis=1)
U = -np.diff(Z[:, 1:], axis=0)
# plot:
fig, ax = plt.subplots()
ax.streamplot(X[1:, 1:], Y[1:, 1:], U, V)
plt.show()