svgbrushablestep
Step chart
How does a level that changes at discrete moments evolve (stock, price, running total)?
How to read it
- Read a flat run as a level holding until the next change.
- Read a vertical jump as the moment the level changed.
- Compare when series change, not only how much.
- Callout 1: A vertical drop: the value changed at this moment.
- 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
# Step chart — Codesplash Chart Lab (recipe "step")
# controls: mode=value, markers=false, zero=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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"
series = [(lv, df[df["sku"].astype(str) == lv]) for lv in freq_levels(df["sku"], 8)]
end = df["timestamp"].max()
fig = go.Figure()
for i, (name, d) in enumerate(series):
d = d.dropna(subset=["timestamp"] + (["on_hand"] if MODE != "count" else [])).sort_values("timestamp", kind="stable")
s = d.groupby("timestamp")["on_hand"].mean() if MODE == "value" else (d.groupby("timestamp")["on_hand"].sum().cumsum() if MODE == "cumsum" else d.groupby("timestamp").size().cumsum())
fig.add_scatter(x=list(s.index) + [end], y=list(s.to_numpy()) + [s.iloc[-1]], mode="lines", line_shape="hv", name=name, line_color=PALETTE[i % len(PALETTE)])
fig.update_yaxes(rangemode="tozero")
fig.update_layout(xaxis_title="timestamp (UTC)")
fig.show()Needs pandas, numpy, plotly · reads step-demo.csv · app theme from the optional codesplash helper
# Step chart — Codesplash Chart Lab (recipe "step")
# controls: mode=value, markers=false, zero=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("step-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["timestamp"]] <- as.POSIXct(df[["timestamp"]], tz = "UTC")
df[["sku"]] <- factor(df[["sku"]], levels = c("A-100", "B-220"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["sku"]], "cs_declared") <- TRUE # stored level order
mode <- "value" # "value" (step-after), "cumsum" or "count" (cumulative rows)
series <- lapply(stats::setNames(nm = freq_levels(df[["sku"]], 8)), function(lv) df[as.character(df[["sku"]]) %in% lv, , drop = FALSE])
end <- max(df[["timestamp"]], na.rm = TRUE) # the last level extends to the end of the axis
steps <- do.call(rbind, lapply(names(series), function(nm) {
d <- series[[nm]]
d <- d[!is.na(d[["timestamp"]]) & (mode == "count" | !is.na(d[["on_hand"]])), , drop = FALSE]
d <- d[order(d[["timestamp"]]), , drop = FALSE]
t <- d[["timestamp"]]
v <- switch(mode, value = tapply(d[["on_hand"]], t, mean), cumsum = cumsum(tapply(d[["on_hand"]], t, sum)), count = cumsum(tapply(t, t, length)))
tt <- sort(unique(t))
data.frame(series = nm, t = c(tt, end), v = c(as.numeric(v), utils::tail(as.numeric(v), 1)))
}))
steps$series <- factor(steps$series, levels = names(series))
p <- ggplot(steps, aes(t, v, colour = series)) +
geom_step(direction = "hv", linewidth = 0.8) + # right-continuous (step-after)
expand_limits(y = 0) +
scale_colour_manual(values = cs_cat, name = "sku") +
labs(x = "timestamp (UTC)", y = if (mode == "value") "on_hand" else if (mode == "cumsum") "cumulative on_hand" else "cumulative rows") +
theme_cs
print(p)Needs ggplot2 · reads step-demo.csv · app theme from the optional codesplashr helper
-- Step chart — Codesplash Chart Lab (recipe "step")
-- controls: mode=value, markers=false, zero=true
-- one level per timestamp (rows sharing a timestamp averaged) plus the cumulative sum and row count
SELECT "sku", "timestamp" AS t,
avg("on_hand") AS value,
sum(sum("on_hand")) OVER (PARTITION BY "sku" ORDER BY "timestamp") AS cumsum,
sum(count(*)) OVER (PARTITION BY "sku" ORDER BY "timestamp") AS cumulative_rows
FROM read_csv('step-demo.csv')
WHERE "timestamp" IS NOT NULL AND "on_hand" IS NOT NULL
GROUP BY "sku", "timestamp"
ORDER BY "sku", "timestamp";Needs duckdb · reads step-demo.csv