How to Make Sparklines and Small Multiples in Python

Draw sparklines with Matplotlib: a stack of tiny line charts with last values, min and max markers, reference bands, a grid of small multiples and inline PNGs for HTML tables.

A sparkline is a tiny line chart without axes that shows the shape of a series next to its name or latest value. In Matplotlib, make one subplot per series with plt.subplots(), plot each line, and call ax.axis("off"). This post uses Matplotlib 3.11 and pandas 3.0.

Quick Example

A year of weekly metrics for a small web shop:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

rng = np.random.default_rng(227)
weeks = pd.date_range("2026-01-05", periods=52, freq="W-MON")

def walk(start, drift, noise):
    return start + np.cumsum(rng.normal(drift, noise, len(weeks)))

metrics = pd.DataFrame({
    "Visitors": walk(4000, 35, 160),
    "Orders": walk(320, 1.5, 14),
    "Avg. order ($)": walk(58, 0.02, 1.1),
    "Returns": walk(30, -0.2, 2.5).clip(min=2),
    "Support tickets": walk(90, 0.1, 6),
}, index=weeks).round(1)

fig, axes = plt.subplots(len(metrics.columns), 1, figsize=(8, 3.8))
for ax, (name, series) in zip(axes, metrics.items()):
    ax.plot(series.index, series, color="#333f50", lw=1.2)
    ax.plot(series.index[-1], series.iloc[-1], "o", color="#d1495b", ms=4)
    ax.axis("off")
    ax.text(-0.02, 0.5, name, transform=ax.transAxes, ha="right", va="center")
    ax.text(1.02, 0.5, f"{series.iloc[-1]:,.0f}", transform=ax.transAxes,
            va="center", fontweight="bold", color="#d1495b")
fig.subplots_adjust(left=0.2, right=0.9, hspace=0.35)
plt.show()

Five stacked sparklines for visitors, orders, average order value, returns and support tickets, each labeled on the left with its latest value on the right

Each row has its own y scale, so sparklines compare shapes, not sizes.

Mark the minimum, maximum and change

fig, axes = plt.subplots(len(metrics.columns), 1, figsize=(8.5, 4.2))
for ax, (name, series) in zip(axes, metrics.items()):
    ax.plot(series.index, series, color="#888888", lw=1.1)
    for when, color in [(series.idxmax(), "#2a9d8f"),
                        (series.idxmin(), "#e76f51")]:
        ax.plot(when, series[when], "o", color=color, ms=5)
    change = series.iloc[-1] / series.iloc[0] - 1
    ax.axis("off")
    ax.margins(y=0.2)
    ax.text(-0.02, 0.5, name, transform=ax.transAxes, ha="right", va="center")
    ax.text(1.02, 0.5, f"{change:+.0%}", transform=ax.transAxes, va="center",
            fontweight="bold")
axes[0].set_title("Past 52 weeks   (green: high, orange: low)", fontsize=10)
fig.subplots_adjust(left=0.2, right=0.9, hspace=0.35)
plt.show()

Sparklines with green dots at each maximum, orange dots at each minimum and the percentage change on the right

Add a normal range band

Shading the middle half of past values shows whether the latest point is unusual.

fig, axes = plt.subplots(len(metrics.columns), 1, figsize=(8, 4))
for ax, (name, series) in zip(axes, metrics.items()):
    low, high = series.quantile([0.25, 0.75])
    ax.axhspan(low, high, color="#cfe1f2")
    ax.plot(series.index, series, color="#1d4e89", lw=1.2)
    ax.axis("off")
    ax.text(-0.02, 0.5, name, transform=ax.transAxes, ha="right", va="center")
fig.subplots_adjust(left=0.2, right=0.98, hspace=0.35)
plt.show()

Sparklines with a light blue band covering the middle half of each metric's values

Small multiples: a grid with shared axes

When the series share a unit, give them the same y scale with sharey=True so heights are comparable. Drawing the others in gray behind each one adds context.

stores = ["Airport", "Bridge St", "Campus", "Depot", "Eastside", "Forum",
          "Garden", "Harbor"]
sales = pd.DataFrame(
    {s: 50 + np.cumsum(rng.normal(rng.uniform(-0.6, 0.9), 2.5, 52))
     for s in stores}, index=weeks)

fig, axes = plt.subplots(2, 4, figsize=(10, 4.8), sharex=True, sharey=True)
for ax, store in zip(axes.flat, stores):
    ax.plot(sales.index, sales, color="#dddddd", lw=0.8)
    ax.plot(sales.index, sales[store], color="#6a4c93", lw=2)
    ax.set_title(store, fontsize=10)
    ax.spines[["top", "right"]].set_visible(False)
    ax.set_xticks([weeks[0], weeks[-1]], ["Jan", "Dec"])
fig.supylabel("Weekly sales ($ thousands)")
fig.tight_layout()
plt.show()

Eight small line charts of store sales with shared axes, each highlighting one store in purple over the others in gray

pandas can do a plain version in one line: sales.plot(subplots=True, layout=(2, 4), sharey=True, legend=False).

Put sparklines in an HTML table

Render each sparkline to PNG in memory and embed it as a base64 string. The result works in reports, emails that allow inline images, and Jupyter.

import base64
import io

def sparkline_img(series, width=1.8, height=0.35):
    fig, ax = plt.subplots(figsize=(width, height), dpi=150)
    ax.plot(series.to_numpy(), color="#1d4e89", lw=1)
    ax.axis("off")
    fig.subplots_adjust(0, 0, 1, 1)
    buffer = io.BytesIO()
    fig.savefig(buffer, format="png", transparent=True)
    plt.close(fig)
    data = base64.b64encode(buffer.getvalue()).decode()
    return f'<img src="data:image/png;base64,{data}" width="180">'

table = pd.DataFrame({
    "Latest": metrics.iloc[-1],
    "Trend": [sparkline_img(metrics[c]) for c in metrics],
})
html = table.to_html(escape=False)
with open("metrics.html", "w") as f:
    f.write(html)

escape=False lets the <img> tags render, so only use it with text you control. For formatted tables with built-in mini charts, see Great Tables.

Practical tips

  • Say what period the sparklines cover, once, near the top.
  • Show at least one number per row. A shape without a value has no scale.
  • Keep markers to the points that matter.
  • For percentages or other bounded values, consider a fixed y range, so small wiggles don't look dramatic.

Similar Topics