Skip to content
svgbrushableline

Line chart

How does a value change over time, and how do series compare?

Demo data · seed 20261101 · 3,276 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the overall direction first, then the repeating ups and downs.
  2. Compare series at the same date, and check the band for how uncertain each one is.
  3. Look at what happens around marked events, without assuming they caused it.
  1. Callout 1: A series' peak; read it against the others at the same date.
  2. Callout 2: Band: the uncertainty or range around the line.
  3. Callout 3: An event marker: a change after it isn't proof of cause.

Watch out

  • Resampling changes what you see: weekly means hide daily spikes.
  • A y axis zoomed away from zero exaggerates small changes.

Defaults

Resample
ISO week
Combine values into days, weeks or months before plotting, to reduce noise.
Also: None (raw) · Day · Month · Quarter
Band
Mean ± 95% CI
What the shaded band around the line shows.
Also: Min–max · None
Points (≤ 120 per series)
Off
Mark individual points when a series has few enough.
Event markers
On
Draw vertical lines at the events you supply.

Pinned in the code

  • Resampling groups rows by the UTC period start (day; ISO week starting Monday; calendar month or quarter) and plots the period mean at the period start.
  • Band “Mean ± 95% CI”: mean ± t(0.975, n − 1)·s/√n of the rows in each period (s with n − 1); periods with one row have no band. Band “Min–max”: the period's range.
  • Without resampling, rows that share a timestamp are averaged and no band is drawn. The first and last periods may be partial (fewer days), which shows as a step at the ends.
  • Event markers: every row whose event column is non-empty draws a dashed reference line labelled with the event and date.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Line chart — Codesplash Chart Lab (recipe "line")
# controls: period=week, band=ci, points=false, events=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("line-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
    """UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
    if period == "none":
        return t
    day = t.dt.floor("D")
    if period == "day":
        return day
    if period == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time

def resample(d, time, value, period, level=0.95):
    """Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
    d = d.dropna(subset=[time, value])
    s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
    s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
    half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
    return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)

PERIOD, BAND = "week", "ci"  # without resampling, rows sharing a timestamp are averaged and no band is drawn
series = [(lv, df[df["region"].astype(str) == lv]) for lv in freq_levels(df["region"], 8)]

fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series):
    s = resample(d, "date", "sales", PERIOD)
    col = PALETTE[i % len(PALETTE)]
    if BAND == "ci":  # mean ± t(0.975, n − 1)·s/√n per period
        ax.fill_between(s["t"], s["lo"], s["hi"], color=col, alpha=0.15, linewidth=0)
    elif BAND == "minmax":
        ax.fill_between(s["t"], s["min"], s["max"], color=col, alpha=0.15, linewidth=0)
    ax.plot(s["t"], s["mean"], color=col, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if len(series) > 1 else "-", label=name)  # dash (and marker) per series, as in the app
events = df.loc[df["event"].notna() & (df["event"].astype(str) != ""), ["date", "event"]].drop_duplicates()
for _, e in events.iterrows():  # dashed reference line per event
    ax.axvline(e["date"], color=REF, linestyle="--", linewidth=1)
    ax.annotate(f"{e["event"]} · {e["date"]:%Y-%m-%d}", (e["date"], 0.98), xycoords=("data", "axes fraction"), ha="left", va="top", fontsize=8, xytext=(3, 0), textcoords="offset points")
ax.set_ylabel("sales")
ax.set_xlabel("date (UTC)")
ax.legend(title="region", fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads line-demo.csv · app theme from the optional codesplash helper