svgtopic-terms
Topic terms
What is each topic about?
How to read it
- Read each panel's top terms to name the topic.
- Compare bar lengths: the most representative terms.
- A term in several panels doesn't distinguish topics.
- Callout 1: This topic's top term.
- Callout 2: The topic's label, for you to check.
- Callout 3: Bars: the term's weight.
Watch out
- Topics are bags of words: the name you give them is your interpretation.
Defaults
- Terms per topic
- 10
- How many terms each topic shows.
- Range 3 to 30, step 1
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Bars are scaled within each panel (the largest term fills the panel); weights are not comparable across topics for NMF.
# Topic terms — Codesplash Chart Lab (recipe "topic-terms")
# controls: top=10
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("topic-terms-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["topic"] = pd.Categorical(df["topic"].astype("string"), categories=["Topic 1 · pricing", "Topic 2 · delivery", "Topic 3 · quality", "Topic 4 · service"])
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)))
TOPIC = "topic"
TERM = "term"
W = "P(word | topic)"
TOP = 10 # terms per topic
d = df.dropna(subset=[TOPIC, TERM, W])
topics = levels_of(d[TOPIC])
ncol = min(4, len(topics))
nrow = int(np.ceil(len(topics) / ncol))
fig, axes = plt.subplots(nrow, ncol, figsize=(3.2 * ncol + 1, 0.28 * TOP * nrow + 1.2), squeeze=False)
for i, ax in enumerate(axes.flat):
if i >= len(topics):
ax.axis("off")
continue
g = d[d[TOPIC].astype(str) == str(topics[i])].nlargest(TOP, W).iloc[::-1]
ax.barh(g[TERM].astype(str), g[W], color=PALETTE[i % len(PALETTE)])
ax.set_title(str(topics[i]), fontsize=9)
ax.tick_params(labelsize=8)
fig.supxlabel(W)
fig.tight_layout()
plt.show()Needs pandas, numpy, matplotlib · reads topic-terms-demo.csv · app theme from the optional codesplash helper
# Topic terms — Codesplash Chart Lab (recipe "topic-terms")
# controls: top=10
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
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("topic-terms-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["topic"] = pd.Categorical(df["topic"].astype("string"), categories=["Topic 1 · pricing", "Topic 2 · delivery", "Topic 3 · quality", "Topic 4 · service"])
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)))
TOPIC = "topic"
TERM = "term"
W = "P(word | topic)"
TOP = 10
d = df.dropna(subset=[TOPIC, TERM, W])
topics = levels_of(d[TOPIC])
ncol = min(4, len(topics))
nrow = int(np.ceil(len(topics) / ncol))
fig = make_subplots(rows=nrow, cols=ncol, subplot_titles=[str(t) for t in topics], horizontal_spacing=0.12)
for i, t in enumerate(topics):
g = d[d[TOPIC].astype(str) == str(t)].nlargest(TOP, W).iloc[::-1]
fig.add_bar(x=g[W], y=g[TERM].astype(str), orientation="h", marker_color=PALETTE[i % len(PALETTE)], showlegend=False, row=i // ncol + 1, col=i % ncol + 1)
fig.show()Needs pandas, numpy, plotly · reads topic-terms-demo.csv · app theme from the optional codesplash helper
# Topic terms — Codesplash Chart Lab (recipe "topic-terms")
# controls: top=10
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("topic-terms-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["topic"]] <- factor(df[["topic"]], levels = c("Topic 1 · pricing", "Topic 2 · delivery", "Topic 3 · quality", "Topic 4 · service"))
df[["term"]] <- factor(df[["term"]])
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
topic_col <- "topic"
term_col <- "term"
w_col <- "P(word | topic)"
top_n <- 10 # terms per topic
d <- df[!is.na(df[[topic_col]]) & !is.na(df[[term_col]]) & !is.na(df[[w_col]]), ]
d <- data.frame(topic = factor(as.character(d[[topic_col]]), levels = levels_of(d[[topic_col]])), term = as.character(d[[term_col]]), w = d[[w_col]])
d <- do.call(rbind, lapply(split(d, d$topic, drop = TRUE), function(g) head(g[order(-g$w), ], top_n)))
d$key <- factor(paste(d$term, d$topic, sep = "___"), levels = rev(unique(paste(d$term, d$topic, sep = "___")))) # order within each panel
p <- ggplot(d, aes(w, key, fill = topic)) + geom_col(width = 0.75) +
facet_wrap(~topic, scales = "free_y") + scale_y_discrete(labels = function(x) sub("___.*$", "", x)) +
scale_fill_manual(values = cs_cat, guide = "none") + labs(x = w_col, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads topic-terms-demo.csv · app theme from the optional codesplashr helper