svgseasonal-subseries
Seasonal subseries (cycle plot)
What is the seasonal pattern, and is each month changing across years?
How to read it
- Each mini line is one month across the years.
- Compare the horizontal segments, the monthly means: they show the seasonal shape.
- Compare the slopes: a steeper month is changing faster across years.
- Callout 1: One month's values, year by year.
- Callout 2: The segment: this month's mean. Peaks here show the season.
Watch out
- With only a few years, a month's mean rests on a few values.
Defaults
- Year points
- On
- Mark each year's value on the mini lines.
Pinned in the code
- Rows are averaged per UTC calendar month; each month's panel plots those monthly means in year order.
- The horizontal segment is the mean of the plotted monthly means (R `monthplot`, `feasts::gg_subseries`).
- Rising mini-lines within a month show trend; differences between segments show seasonality.
- All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Seasonal subseries (cycle plot) — Codesplash Chart Lab (recipe "seasonal-subseries")
# controls: points=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("seasonal-subseries-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"])
X, Y = "month", "passengers_k"
d = df.dropna(subset=[X, Y])
monthly = d.groupby(d[X].dt.to_period("M"))[Y].mean() # mean per UTC calendar month
sub = pd.DataFrame({"year": monthly.index.year, "month": monthly.index.month, "value": monthly.to_numpy()})
month_mean = sub.groupby("month")["value"].mean() # the horizontal segment: mean of the monthly means
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
fig, ax = plt.subplots(figsize=(9, 4))
for m in range(1, 13):
pts = sub[sub["month"] == m].sort_values("year")
if pts.empty:
continue
xs = m + np.linspace(-0.35, 0.35, len(pts)) if len(pts) > 1 else np.array([m]) # years in order within the month
ax.plot(xs, pts["value"], color=PALETTE[0], linewidth=1.3, marker="o", markersize=3)
ax.hlines(month_mean[m], m - 0.38, m + 0.38, color=PALETTE[1], linewidth=2)
ax.set_xticks(range(1, 13), MONTHS)
ax.set_ylabel("passengers_k" + " (monthly mean)")
plt.show()Needs pandas, numpy, matplotlib · reads seasonal-subseries-demo.csv · app theme from the optional codesplash helper
# Seasonal subseries (cycle plot) — Codesplash Chart Lab (recipe "seasonal-subseries")
# controls: points=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("seasonal-subseries-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"])
X, Y = "month", "passengers_k"
d = df.dropna(subset=[X, Y])
monthly = d.groupby(d[X].dt.to_period("M"))[Y].mean() # mean per UTC calendar month
sub = pd.DataFrame({"year": monthly.index.year, "month": monthly.index.month, "value": monthly.to_numpy()})
month_mean = sub.groupby("month")["value"].mean() # the horizontal segment: mean of the monthly means
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
fig = go.Figure()
for m in range(1, 13):
pts = sub[sub["month"] == m].sort_values("year")
if pts.empty:
continue
xs = m + np.linspace(-0.35, 0.35, len(pts)) if len(pts) > 1 else np.array([m])
fig.add_scatter(x=xs, y=pts["value"], mode="lines+markers", line_color=PALETTE[0], text=pts["year"], showlegend=False, hovertemplate="%{text}: %{y}<extra></extra>")
fig.add_scatter(x=[m - 0.38, m + 0.38], y=[month_mean[m]] * 2, mode="lines", line=dict(color=PALETTE[1], width=3), showlegend=False)
fig.update_layout(xaxis=dict(tickvals=list(range(1, 13)), ticktext=MONTHS), yaxis_title=Y + " (monthly mean)")
fig.show()Needs pandas, numpy, plotly · reads seasonal-subseries-demo.csv · app theme from the optional codesplash helper
# Seasonal subseries (cycle plot) — Codesplash Chart Lab (recipe "seasonal-subseries")
# controls: points=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("seasonal-subseries-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")
t <- as.POSIXlt(df[["month"]], tz = "UTC")
ok <- !is.na(t) & !is.na(df[["passengers_k"]])
key <- sprintf("%d-%02d", t$year[ok] + 1900, t$mon[ok] + 1)
m <- tapply(df[["passengers_k"]][ok], key, mean) # mean per UTC calendar month
sub <- data.frame(year = as.integer(substr(names(m), 1, 4)), month = as.integer(substr(names(m), 6, 7)), value = as.numeric(m))
sub$month <- factor(month.abb[sub$month], levels = month.abb)
seg <- stats::aggregate(value ~ month, sub, mean) # mean of the monthly means (R monthplot)
p <- ggplot(sub, aes(year, value)) +
geom_hline(data = seg, aes(yintercept = value), colour = cs_cat[2], linewidth = 0.9) +
geom_line(colour = cs_cat[1]) +
geom_point(colour = cs_cat[1], size = 1) +
facet_wrap(~month, nrow = 1) +
labs(x = NULL, y = "passengers_k (monthly mean)") +
theme_cs + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank())
print(p)Needs ggplot2 · reads seasonal-subseries-demo.csv · app theme from the optional codesplashr helper
-- Seasonal subseries (cycle plot) — Codesplash Chart Lab (recipe "seasonal-subseries")
-- controls: points=true
-- monthly means per year and, per calendar month, the mean of those means
WITH m AS (
SELECT year("month") AS year, month("month") AS month, avg("passengers_k") AS value
FROM read_csv('seasonal-subseries-demo.csv') WHERE "month" IS NOT NULL AND "passengers_k" IS NOT NULL
GROUP BY ALL
)
SELECT month, year, value, avg(value) OVER (PARTITION BY month) AS month_mean
FROM m
ORDER BY month, year;Needs duckdb · reads seasonal-subseries-demo.csv