Skip to content
svgbrushablestep

Step chart

How does a level that changes at discrete moments evolve (stock, price, running total)?

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

How to read it

  1. Read a flat run as a level holding until the next change.
  2. Read a vertical jump as the moment the level changed.
  3. Compare when series change, not only how much.
  1. Callout 1: A vertical drop: the value changed at this moment.
  2. Callout 2: A flat run: no change until the next step.

Watch out

  • Don't interpolate between steps: the value held, it did not slide.

Defaults

Plot
Value (step-after)
What to plot: the values, their running sum or a running count.
Also: Cumulative sum · Cumulative rows
Change markers
Off
Mark the moments when the level changes.
Zero baseline
On
Start the y axis at zero.

Pinned in the code

  • Step-after (right-continuous): a value recorded at time t holds until the next timestamp (matplotlib `where="post"`, ggplot2 `geom_step(direction = "hv")`); the last level extends to the end of the axis.
  • Rows sharing a timestamp are averaged in value mode; cumulative modes add them in time order.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Step chart — Codesplash Chart Lab (recipe "step")
# controls: mode=value, markers=false, zero=true
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("step-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["timestamp"] = pd.to_datetime(df["timestamp"])
df["sku"] = pd.Categorical(df["sku"].astype("string"), categories=["A-100", "B-220"])

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]

MODE = "value"  # "value" (step-after), "cumsum" or "count" (cumulative rows)
series = [(lv, df[df["sku"].astype(str) == lv]) for lv in freq_levels(df["sku"], 8)]
end = df["timestamp"].max()  # the last level extends to the end of the axis
fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series):
    d = d.dropna(subset=["timestamp"] + (["on_hand"] if MODE != "count" else [])).sort_values("timestamp", kind="stable")
    if MODE == "value":  # rows sharing a timestamp are averaged
        s = d.groupby("timestamp")["on_hand"].mean()
    elif MODE == "cumsum":
        s = d.groupby("timestamp")["on_hand"].sum().cumsum()
    else:
        s = d.groupby("timestamp").size().cumsum()
    t = list(s.index) + [end]
    v = list(s.to_numpy()) + [s.iloc[-1]]
    ax.step(t, v, where="post", color=PALETTE[i % len(PALETTE)], linewidth=1.6, label=name)  # right-continuous
ax.set_ylim(bottom=min(0, ax.get_ylim()[0]))  # zero baseline
ax.set_xlabel("timestamp (UTC)")
ax.set_ylabel("on_hand" if MODE == "value" else ("cumulative " + "on_hand" if MODE == "cumsum" else "cumulative rows"))
ax.legend(title="sku", fontsize=8)
plt.show()

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