svgsegment-means
Series with segment means
Where does the level of the series change, and what is the level in each segment?
How to read it
- Read the horizontal lines as each segment's mean.
- Read the dashed lines as the estimated change dates.
- Compare levels and whether variability differs across segments.
- Callout 1: A dashed line: an estimated change.
- Callout 2: This segment's mean.
- 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
# Series with segment means — Codesplash Chart Lab (recipe "segment-means")
# controls: defaults
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("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()
fig = go.Figure(go.Scatter(x=t, y=d[Y], mode="lines", line=dict(color=PALETTE[0], width=1.2), name=Y))
for r, g in d.groupby(run, sort=True):
tt = t[g.index]
fig.add_scatter(x=[tt.iloc[0], tt.iloc[-1]], y=[g[Y].mean()] * 2, mode="lines", line=dict(color=PALETTE[3 % len(PALETTE)], width=3), showlegend=False)
fig.update_layout(xaxis_title="week", yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads segment-means-demo.csv · app theme from the optional codesplash helper
# Series with segment means — Codesplash Chart Lab (recipe "segment-means")
# controls: defaults
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("segment-means-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["week"]] <- as.POSIXct(df[["week"]], tz = "UTC")
df[["segment"]] <- factor(df[["segment"]], levels = c("1", "2", "3"))
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
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 <- "week"
y_col <- "level"
seg_col <- "segment"
d <- ordered(df, x_col, c(y_col, seg_col))
d$t <- time_of(d, x_col)
seg <- if (is.null(seg_col)) rep("1", nrow(d)) else as.character(d[[seg_col]])
d$run <- cumsum(c(TRUE, seg[-1] != seg[-length(seg)])) # consecutive runs of the same label
runs <- do.call(rbind, lapply(split(d, d$run), function(g) data.frame(t0 = g$t[1], t1 = g$t[nrow(g)], mean = mean(g[[y_col]]))))
p <- ggplot(d, aes(t, .data[[y_col]])) + geom_line(colour = cs_cat[1], alpha = 0.7) +
geom_segment(data = runs, aes(x = t0, xend = t1, y = mean, yend = mean), colour = cs_cat[min(4, length(cs_cat))], linewidth = 1.3, inherit.aes = FALSE) +
labs(x = "week", y = y_col) + theme_cs
print(p)Needs ggplot2 · reads segment-means-demo.csv · app theme from the optional codesplashr helper