Skip to content
svgsegment-means

Series with segment means

Where does the level of the series change, and what is the level in each segment?

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

How to read it

  1. Read the horizontal lines as each segment's mean.
  2. Read the dashed lines as the estimated change dates.
  3. Compare levels and whether variability differs across segments.
  1. Callout 1: A dashed line: an estimated change.
  2. Callout 2: This segment's mean.
  3. Callout 3: The next segment's level.

Watch out

  • Segmentation finds changes by design. The penalty setting controls how many, so try more than one.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Segments are runs of the same label in time order; each line spans its first to last observation at the segment mean.
  • Dashed lines sit on the last observation before each change, as the analyses report change points.
# Series with segment means — Codesplash Chart Lab (recipe "segment-means")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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"]

df = pd.read_csv("segment-means-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["week"] = pd.to_datetime(df["week"])
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["1", "2", "3"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "week"
Y = "level"
SEG = "segment"
d = ordered(df, X, [Y, SEG])
t = time_of(d, X)
seg = d[SEG].astype(str) if SEG else pd.Series("1", index=d.index)
run = (seg != seg.shift()).cumsum()  # consecutive runs of the same label
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t, d[Y], color=PALETTE[0], alpha=0.7, linewidth=1.2)
for r, g in d.groupby(run, sort=True):
    tt = t[g.index]
    ax.hlines(g[Y].mean(), tt.iloc[0], tt.iloc[-1], color=PALETTE[3 % len(PALETTE)], linewidth=2.6)
    if r > 1:
        ax.axvline(t[d.index[d.index.get_loc(g.index[0]) - 1]], color=REF, linestyle="--", linewidth=1)
ax.set_xlabel("week")
ax.set_ylabel(Y)
plt.show()

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