How to Make a Stream Graph in Python with Matplotlib

Draw stream graphs with stackplot, compare the four baseline options, smooth the layers and label them directly.

A stream graph is a stacked area chart whose baseline floats around the center instead of sitting at zero. In Matplotlib, make one with ax.stackplot(x, ys, baseline="wiggle"). This post uses Matplotlib 3.11 and SciPy 1.18.

Quick Example

Monthly hours played by game genre at a made-up gaming café:

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(197)
months = np.arange(36)
genres = ["Strategy", "Racing", "Puzzle", "Shooter", "Co-op", "Sports"]

# Each genre rises and fades around its own peak month
peaks = [4, 10, 16, 21, 28, 33]
widths = [9, 7, 12, 8, 7, 10]
heights = [70, 45, 40, 90, 75, 50]
hours = np.array([
    h * np.exp(-((months - p) / w) ** 2) + 8 + rng.normal(0, 0.6, 36)
    for p, w, h in zip(peaks, widths, heights)
]).clip(min=0)

colors = ["#264653", "#2a9d8f", "#8ab17d", "#e9c46a", "#f4a261", "#e76f51"]

fig, ax = plt.subplots(figsize=(9, 4.5))
ax.stackplot(months, hours, labels=genres, colors=colors, baseline="wiggle")
ax.set_xlabel("Month")
ax.set_yticks([])
ax.spines[["left", "right", "top"]].set_visible(False)
ax.margins(x=0)
ax.legend(loc="upper left", ncols=6, fontsize=9, frameon=False)
ax.set_ylim(top=ax.get_ylim()[1] * 1.2)
plt.show()

Stream graph of monthly hours for six game genres, with each genre swelling and then fading in turn across 36 months

The thickness of a band is its value. Its vertical position has no meaning, so the y-axis ticks are removed.

What do the baseline options do?

stackplot() accepts four values for baseline:

baselines = {
    "zero": "Ordinary stacked area chart",
    "sym": "Centered around zero",
    "wiggle": "Reduces the slopes of the layers",
    "weighted_wiggle": "Same, weighted by layer size (streamgraph)",
}

fig, axes = plt.subplots(2, 2, figsize=(10, 6))
for ax, (name, note) in zip(axes.flat, baselines.items()):
    ax.stackplot(months, hours, colors=colors, baseline=name)
    ax.set_title(f'baseline="{name}"\n{note}', fontsize=10)
    ax.set_xticks([])
    ax.margins(x=0)
fig.tight_layout()
plt.show()

Four versions of the same data with zero, sym, wiggle and weighted_wiggle baselines

"sym" is easy to explain because the shape is a mirror image around the middle. "weighted_wiggle" is designed to keep thick layers from jumping around, though with this data, where one genre replaces another, the whole stream drifts downward. Try each on your own data.

Smooth the layers

PchipInterpolator draws smooth curves through your points without overshooting, so values never dip below zero between months. An ordinary cubic spline can overshoot.

from scipy.interpolate import PchipInterpolator

fine = np.linspace(months.min(), months.max(), 600)
smooth = PchipInterpolator(months, hours, axis=1)(fine)

fig, ax = plt.subplots(figsize=(9, 4.5))
ax.stackplot(fine, smooth, labels=genres, colors=colors,
             baseline="wiggle")
ax.set_xlabel("Month")
ax.set_yticks([])
ax.spines[["left", "right", "top"]].set_visible(False)
ax.margins(x=0)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncols=6, fontsize=9,
          frameon=False)
plt.show()

Smoothed stream graph with a wiggle baseline and a legend above the chart

Label the layers directly

To write names inside the bands, work out where each band sits from the data, then place the text at its thickest point.

fig, ax = plt.subplots(figsize=(9, 4.5))
ax.stackplot(fine, smooth, colors=colors, baseline="sym")

# With baseline="sym", the stack starts at minus half the total
bottom = -smooth.sum(axis=0) / 2
tops = bottom + smooth.cumsum(axis=0)

for i, genre in enumerate(genres):
    # Keep labels away from the left and right edges
    j = 40 + smooth[i, 40:-40].argmax()
    middle = tops[i, j] - smooth[i, j] / 2
    ax.text(fine[j], middle, genre, ha="center", va="center", fontsize=10,
            color="white" if i in (0, 1) else "black")

ax.set_xlabel("Month")
ax.set_yticks([])
ax.spines[["left", "right", "top"]].set_visible(False)
ax.margins(x=0)
plt.show()

Centered stream graph with each genre name written inside its band at its thickest point

Stream graph, stacked area or small multiples?

Goal Chart
Show how a mix shifts over time, as an overview Stream graph
Read the total accurately Stacked area chart with a zero baseline
Compare individual series precisely Small multiples or lines
Show shares of 100% Percentage stacked area

Practical tips

  • Use stream graphs for shape and timing. Readers can't measure values from a floating baseline.
  • Order layers on purpose: by start time, as here, or with the most volatile on the outside.
  • All values must be zero or positive.
  • Beyond eight or so layers, group the small ones into "Other".

Similar Topics