svgtopics-over-time
Topics over time
Which topics are growing or fading?
How to read it
- Read a band's thickness as that topic's share or count in that period.
- A widening band is a rising topic; the bottom band is the easiest to read.
- Switch between share and counts: a share can fall while the count rises.
- Callout 1: The largest topic, at the bottom.
- Callout 2: A band that thins: this topic is fading.
Watch out
- Topics come from a model, so check that a topic means the same thing throughout the period.
Defaults
- Show
- Share of each period
- Shares show which topics rise relative to the rest, even if the total volume changes.
- Also: Counts
- Topics shown
- 6
- Smaller topics are grouped into Other.
- Range 2 to 12, step 1
Pinned in the code
- Rows are summed per period and topic; topics are ranked by total weight, largest at the bottom.
- Topics beyond the top N join Other. Periods are as given: bin dates before charting.
# Topics over time — Codesplash Chart Lab (recipe "topics-over-time")
# controls: mode=share, top=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
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_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5) # stripes let the chart surface show through
df = pd.read_csv("topics-over-time-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"])
T = "month"
K = "topic"
W = "tickets"
TOP, SHARE = 6, True
d = df.dropna(subset=[T, K]).assign(_w=lambda f: f[W].astype(float) if W else 1.0)
totals = d.groupby(K)["_w"].sum().sort_values(ascending=False)
keep = list(totals.index[:TOP])
d["_k"] = d[K].where(d[K].isin(keep), "Other")
wide = d.pivot_table(index=T, columns="_k", values="_w", aggfunc="sum", fill_value=0).sort_index()
wide = wide[keep + (["Other"] if "Other" in wide else [])] # largest topic at the bottom
if SHARE:
wide = wide.div(wide.sum(axis=1), axis=0)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.stackplot(wide.index, wide.T.to_numpy(), labels=wide.columns, colors=PALETTE, alpha=0.85, hatch=[SERIES_HATCHES[i % 8] for i in range(wide.shape[1])], hatchcolor=HATCH_INK, linewidth=0) # texture per topic, as in the app
ax.set_xlabel(T)
ax.set_ylabel("share" if SHARE else "count")
ax.legend(fontsize=8, loc="upper left")
plt.show()Needs pandas, numpy, matplotlib · reads topics-over-time-demo.csv · app theme from the optional codesplash helper
# Topics over time — Codesplash Chart Lab (recipe "topics-over-time")
# controls: mode=share, top=6
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("topics-over-time-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"])
T = "month"
K = "topic"
W = "tickets"
TOP, SHARE = 6, True
d = df.dropna(subset=[T, K]).assign(_w=lambda f: f[W].astype(float) if W else 1.0)
totals = d.groupby(K)["_w"].sum().sort_values(ascending=False)
keep = list(totals.index[:TOP])
d["_k"] = d[K].where(d[K].isin(keep), "Other")
wide = d.pivot_table(index=T, columns="_k", values="_w", aggfunc="sum", fill_value=0).sort_index()
wide = wide[keep + (["Other"] if "Other" in wide else [])] # largest topic at the bottom
if SHARE:
wide = wide.div(wide.sum(axis=1), axis=0)
fig = go.Figure()
for i, k in enumerate(wide.columns):
fig.add_scatter(x=wide.index, y=wide[k], mode="lines", stackgroup="one", name=str(k), line=dict(color=PALETTE[i % len(PALETTE)], width=0.5),
fillpattern=dict(shape=SERIES_HATCHES[i % 8], fgcolor=HATCH_INK, fillmode="overlay")) # texture per topic, as in the app
fig.update_layout(xaxis_title=T, yaxis_title="share" if SHARE else "count")
fig.show()Needs pandas, numpy, plotly · reads topics-over-time-demo.csv · app theme from the optional codesplash helper
# Topics over time — Codesplash Chart Lab (recipe "topics-over-time")
# controls: mode=share, top=6
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_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("topics-over-time-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")
df[["topic"]] <- factor(df[["topic"]])
T <- "month"
K <- "topic"
W <- "tickets"
TOP <- 6; SHARE <- TRUE
d <- data.frame(t = df[[T]], k = as.character(df[[K]]), w = if (is.null(W)) 1 else df[[W]])
d <- d[!is.na(d$t) & !is.na(d$k), ]
totals <- sort(tapply(d$w, d$k, sum), decreasing = TRUE)
keep <- names(totals)[seq_len(min(TOP, length(totals)))]
d$k[!d$k %in% keep] <- "Other"
a <- aggregate(w ~ t + k, d, sum)
lv <- c(keep, if ("Other" %in% a$k) "Other")
a$k <- factor(a$k, levels = rev(lv)) # largest topic at the bottom
full <- merge(expand.grid(t = unique(a$t), k = levels(a$k)), a, all.x = TRUE)
full$w[is.na(full$w)] <- 0
full$k <- factor(full$k, levels = rev(lv))
p <- ggplot(full, aes(t, w, fill = k)) +
geom_area(position = if (SHARE) "fill" else "stack", alpha = 0.85) +
scale_fill_manual(values = setNames(cs_textures(rep_len(cs_cat, length(lv))), lv), name = NULL) + # texture per topic, as in the app
labs(x = T, y = if (SHARE) "share" else "count") + theme_cs
print(p)Needs ggplot2 · reads topics-over-time-demo.csv · app theme from the optional codesplashr helper