svgseries-line
Series with break marker
How does the series move over time, and where is an estimated break?
How to read it
- Read the level and any drift in the series.
- Look for a marked break after an estimated date.
- Compare the level before and after that mark.
- Callout 1: The level shifts around here.
- Callout 2: After the shift, the series varies around a higher level.
Watch out
- A break found by searching all dates isn't an independent test of that date.
Defaults
- Break after observation (0 = none)
- 0
- 1-based position in time order of the last observation before the break.
- Range 0 to 100,000, step 1
- Show points
- Off
- Mark the individual observations on the line.
Pinned in the code
- Rows are sorted by the time column (row order when absent); missing values break the line.
- Time may be dates or numbers (years, hours, positions): the axis follows the column's kind.
- The break marker sits on the last observation before the break, as Zivot–Andrews reports it.
# Series with break marker — Codesplash Chart Lab (recipe "series-line")
# controls: marker=0, points=false
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("series-line-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
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 = "month"
Y = "index"
G = None
MARKER, POINTS = 0, False # break after this position (0 = none)
d = ordered(df, X, [Y, G])
groups = levels_of(d[G]) if G else [None]
fig, ax = plt.subplots(figsize=(8, 4))
for i, g in enumerate(groups):
s = d if g is None else d[d[G].astype(str) == str(g)]
ax.plot(time_of(s, X), s[Y], color=PALETTE[i % len(PALETTE)], linewidth=1.6, label=None if g is None else str(g))
if POINTS and i == 0:
ax.scatter(time_of(s, X), s[Y], s=6, color=PALETTE[0])
first = d if G is None else d[d[G].astype(str) == str(groups[0])]
if 0 < MARKER <= len(first):
ax.axvline(time_of(first, X).iloc[MARKER - 1], color=REF, linestyle="--", linewidth=1.2, label="estimated break")
ax.set_xlabel("month")
ax.set_ylabel(Y)
if G or MARKER:
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads series-line-demo.csv · app theme from the optional codesplash helper
# Series with break marker — Codesplash Chart Lab (recipe "series-line")
# controls: marker=0, points=false
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("series-line-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
_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 levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
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 = "month"
Y = "index"
G = None
MARKER, POINTS = 0, False
d = ordered(df, X, [Y, G])
groups = levels_of(d[G]) if G else [None]
fig = go.Figure()
for i, g in enumerate(groups):
s = d if g is None else d[d[G].astype(str) == str(g)]
fig.add_scatter(x=time_of(s, X), y=s[Y], mode="lines+markers" if POINTS and i == 0 else "lines", name=str(g) if g is not None else Y,
line=dict(color=PALETTE[i % len(PALETTE)], width=1.6), marker=dict(size=4))
first = d if G is None else d[d[G].astype(str) == str(groups[0])]
if 0 < MARKER <= len(first):
fig.add_vline(x=time_of(first, X).iloc[MARKER - 1], line=dict(color=REF, dash="dash"), annotation_text="estimated break")
fig.update_layout(xaxis_title="month", yaxis_title=Y, showlegend=bool(G))
fig.show()Needs pandas, numpy, plotly · reads series-line-demo.csv · app theme from the optional codesplash helper
# Series with break marker — Codesplash Chart Lab (recipe "series-line")
# controls: marker=0, points=false
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("series-line-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "month"
y_col <- "index"
g_col <- NULL
MARKER <- 0 # break after this position (0 = none)
POINTS <- FALSE
d <- ordered(df, x_col, c(y_col, g_col))
d$t <- time_of(d, x_col)
if (!is.null(g_col) && is.null(x_col)) d$t <- ave(seq_len(nrow(d)), as.character(d[[g_col]]), FUN = seq_along) # each series' own positions
first <- if (is.null(g_col)) d else d[as.character(d[[g_col]]) == levels_of(d[[g_col]])[1], , drop = FALSE]
p <- ggplot(d, aes(t, .data[[y_col]])) +
{ if (is.null(g_col)) geom_line(colour = cs_cat[1], linewidth = 0.8) else geom_line(aes(colour = factor(.data[[g_col]], levels = levels_of(.data[[g_col]]))), linewidth = 0.8) } +
{ if (POINTS) geom_point(data = first, colour = cs_cat[1], size = 0.8) } +
{ if (MARKER > 0 && MARKER <= nrow(first)) geom_vline(xintercept = first$t[MARKER], colour = ref_col, linetype = "dashed") } +
scale_colour_manual(values = cs_cat, name = NULL) + labs(x = "month", y = y_col) + theme_cs
print(p)Needs ggplot2 · reads series-line-demo.csv · app theme from the optional codesplashr helper