svgbrushableline
Line chart
How does a value change over time, and how do series compare?
How to read it
- Read the overall direction first, then the repeating ups and downs.
- Compare series at the same date, and check the band for how uncertain each one is.
- Look at what happens around marked events, without assuming they caused it.
- Callout 1: A series' peak; read it against the others at the same date.
- Callout 2: Band: the uncertainty or range around the line.
- Callout 3: An event marker: a change after it isn't proof of cause.
Watch out
- Resampling changes what you see: weekly means hide daily spikes.
- A y axis zoomed away from zero exaggerates small changes.
Defaults
- Resample
- ISO week
- Combine values into days, weeks or months before plotting, to reduce noise.
- Also: None (raw) · Day · Month · Quarter
- Band
- Mean ± 95% CI
- What the shaded band around the line shows.
- Also: Min–max · None
- Points (≤ 120 per series)
- Off
- Mark individual points when a series has few enough.
- Event markers
- On
- Draw vertical lines at the events you supply.
Pinned in the code
- Resampling groups rows by the UTC period start (day; ISO week starting Monday; calendar month or quarter) and plots the period mean at the period start.
- Band “Mean ± 95% CI”: mean ± t(0.975, n − 1)·s/√n of the rows in each period (s with n − 1); periods with one row have no band. Band “Min–max”: the period's range.
- Without resampling, rows that share a timestamp are averaged and no band is drawn. The first and last periods may be partial (fewer days), which shows as a step at the ends.
- Event markers: every row whose event column is non-empty draws a dashed reference line labelled with the event and date.
- All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Line chart — Codesplash Chart Lab (recipe "line")
# controls: period=week, band=ci, points=false, events=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
df = pd.read_csv("line-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])
_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 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]
def period_start(t, period):
"""UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
if period == "none":
return t
day = t.dt.floor("D")
if period == "day":
return day
if period == "week":
return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time
def resample(d, time, value, period, level=0.95):
"""Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
d = d.dropna(subset=[time, value])
s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)
PERIOD, BAND = "week", "ci" # without resampling, rows sharing a timestamp are averaged and no band is drawn
series = [(lv, df[df["region"].astype(str) == lv]) for lv in freq_levels(df["region"], 8)]
fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series):
s = resample(d, "date", "sales", PERIOD)
col = PALETTE[i % len(PALETTE)]
if BAND == "ci": # mean ± t(0.975, n − 1)·s/√n per period
ax.fill_between(s["t"], s["lo"], s["hi"], color=col, alpha=0.15, linewidth=0)
elif BAND == "minmax":
ax.fill_between(s["t"], s["min"], s["max"], color=col, alpha=0.15, linewidth=0)
ax.plot(s["t"], s["mean"], color=col, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if len(series) > 1 else "-", label=name) # dash (and marker) per series, as in the app
events = df.loc[df["event"].notna() & (df["event"].astype(str) != ""), ["date", "event"]].drop_duplicates()
for _, e in events.iterrows(): # dashed reference line per event
ax.axvline(e["date"], color=REF, linestyle="--", linewidth=1)
ax.annotate(f"{e["event"]} · {e["date"]:%Y-%m-%d}", (e["date"], 0.98), xycoords=("data", "axes fraction"), ha="left", va="top", fontsize=8, xytext=(3, 0), textcoords="offset points")
ax.set_ylabel("sales")
ax.set_xlabel("date (UTC)")
ax.legend(title="region", fontsize=8)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads line-demo.csv · app theme from the optional codesplash helper
# Line chart — Codesplash Chart Lab (recipe "line")
# controls: period=week, band=ci, points=false, events=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
df = pd.read_csv("line-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])
_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 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]
def period_start(t, period):
"""UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
if period == "none":
return t
day = t.dt.floor("D")
if period == "day":
return day
if period == "week":
return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time
def resample(d, time, value, period, level=0.95):
"""Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
d = d.dropna(subset=[time, value])
s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
PERIOD, BAND = "week", "ci"
series = [(lv, df[df["region"].astype(str) == lv]) for lv in freq_levels(df["region"], 8)]
fig = go.Figure()
for i, (name, d) in enumerate(series):
s = resample(d, "date", "sales", PERIOD)
col = PALETTE[i % len(PALETTE)]
if BAND != "none":
lo, hi = (s["lo"], s["hi"]) if BAND == "ci" else (s["min"], s["max"])
fig.add_scatter(x=s["t"], y=lo, mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=s["t"], y=hi, mode="lines", line_width=0, fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=s["t"], y=s["mean"], mode="lines", name=name, line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if len(series) > 1 else "solid")) # dash per series, as in the app
events = df.loc[df["event"].notna() & (df["event"].astype(str) != ""), ["date", "event"]].drop_duplicates()
for _, e in events.iterrows():
fig.add_shape(type="line", x0=e["date"], x1=e["date"], y0=0, y1=1, yref="paper", line=dict(color=REF, dash="dash", width=1))
fig.add_annotation(x=e["date"], y=1, yref="paper", text=f"{e["event"]} · {e["date"]:%Y-%m-%d}", showarrow=False, xanchor="left", yanchor="top", font_size=10)
fig.update_layout(xaxis_title="date (UTC)", yaxis_title="sales")
fig.show()Needs pandas, numpy, plotly, scipy · reads line-demo.csv · app theme from the optional codesplash helper
# Line chart — Codesplash Chart Lab (recipe "line")
# controls: period=week, band=ci, points=false, events=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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("line-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))
df[["event"]] <- factor(df[["event"]])
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
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[["region"]], "cs_declared") <- TRUE # stored level order
period_start <- function(t, period) {
# UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp
t <- as.POSIXct(t, tz = "UTC")
if (period == "none") return(t)
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(period,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
resample_stats <- function(t, v, period, level = 0.95) {
# per period: n, mean, SD (n - 1), min, max and mean ± t(0.975, n - 1)·SD/√n (no band when n = 1)
ok <- !is.na(t) & is.finite(v)
k <- as.numeric(period_start(t[ok], period))
out <- do.call(rbind, lapply(split(v[ok], k), function(s) {
n <- length(s); sdv <- if (n > 1) stats::sd(s) else 0
half <- if (n > 1) stats::qt(1 - (1 - level) / 2, n - 1) * sdv / sqrt(n) else 0
data.frame(n = n, mean = mean(s), sd = sdv, min = min(s), max = max(s), lo = mean(s) - half, hi = mean(s) + half)
}))
out$t <- as.POSIXct(as.numeric(names(split(v[ok], k))), origin = "1970-01-01", tz = "UTC")
out[order(out$t), , drop = FALSE]
}
period <- "week"; band <- "ci" # without resampling, rows sharing a timestamp are averaged, no band
series <- lapply(stats::setNames(nm = freq_levels(df[["region"]], 8)), function(lv) df[as.character(df[["region"]]) %in% lv, , drop = FALSE])
stats_df <- do.call(rbind, lapply(names(series), function(nm) cbind(series = nm, resample_stats(series[[nm]][["date"]], series[[nm]][["sales"]], period))))
stats_df$series <- factor(stats_df$series, levels = names(series))
if (band == "minmax") { stats_df$lo <- stats_df$min; stats_df$hi <- stats_df$max }
p <- ggplot(stats_df, aes(t, mean, colour = series, fill = series)) +
{ if (band != "none") geom_ribbon(aes(ymin = lo, ymax = hi), alpha = 0.15, colour = NA) } +
geom_line(aes(linetype = series), linewidth = 0.8) + # dash per series, as in the app
geom_vline(data = unique(df[!is.na(df[["event"]]) & df[["event"]] != "", c("date", "event")]), aes(xintercept = .data[["date"]]), colour = ref_col, linetype = "dashed") +
geom_text(data = unique(df[!is.na(df[["event"]]) & df[["event"]] != "", c("date", "event")]), aes(x = .data[["date"]], y = Inf, label = paste(.data[["event"]], format(.data[["date"]], "%Y-%m-%d"), sep = " · ")), hjust = -0.05, vjust = 1.5, size = 3, inherit.aes = FALSE) +
scale_colour_manual(values = cs_cat, name = "region") + scale_fill_manual(values = cs_cat, guide = "none") +
scale_linetype_manual(values = cs_linetypes, name = "region") +
labs(x = "date (UTC)", y = "sales") +
theme_cs
print(p)Needs ggplot2 · reads line-demo.csv · app theme from the optional codesplashr helper
-- Line chart — Codesplash Chart Lab (recipe "line")
-- controls: period=week, band=ci, points=false, events=true
-- per-period statistics (UTC); CI = mean ± t(0.975, n − 1)·se is computed on the client
SELECT "region", date_trunc('week', "date") AS t,
count("sales") AS n, avg("sales") AS mean, stddev_samp("sales") AS sd,
stddev_samp("sales") / sqrt(count("sales")) AS se, min("sales") AS min, max("sales") AS max,
string_agg(DISTINCT "event", ', ') FILTER (WHERE "event" <> '') AS events
FROM read_csv('line-demo.csv')
WHERE "date" IS NOT NULL AND "sales" IS NOT NULL
GROUP BY ALL
ORDER BY ALL;Needs duckdb · reads line-demo.csv