svgngram-bars
Top terms
Which words or phrases appear most in a text column, overall or by group?
How to read it
- Read bars as the most frequent terms per group.
- Compare panels: what's distinctive to each group?
- Use TF-IDF to look past words common to all groups.
- Callout 1: The most frequent term in this group.
- Callout 2: The other group's top term.
- Callout 3: Rarer terms.
Watch out
- Frequency isn't importance, and terms lose their context.
Defaults
- Terms per panel
- 20
- How many terms each panel shows.
- Range 3 to 50, step 1
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine or the host's scorecard); the chart computes nothing statistical.
- Counts of the same term within a group are summed; ties are broken alphabetically. Tokenization (lowercasing, stop words, n-gram length) is the engine's — see the method's options.
# Top terms — Codesplash Chart Lab (recipe "ngram-bars")
# controls: top=20
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("ngram-bars-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["rating"] = pd.Categorical(df["rating"].astype("string"), categories=["1–2 stars", "4–5 stars"])
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)))
TERM = "bigram"
N = "count"
G = "rating"
TOP = 20
groups = levels_of(df[G]) if G else [None]
fig, axes = plt.subplots(1, len(groups), figsize=(4 * len(groups) + 1, 5), squeeze=False)
for i, (ax, g) in enumerate(zip(axes[0], groups)):
d = (df if g is None else df[df[G].astype(str) == str(g)]).groupby(TERM, observed=True)[N].sum().reset_index()
d = d.sort_values([N, TERM], ascending=[False, True]).head(TOP).iloc[::-1] # largest on top
ax.barh(d[TERM].astype(str), d[N], color=PALETTE[i % len(PALETTE)])
ax.set_title(str(g) if g is not None else "", fontsize=10, loc="left")
ax.set_xlabel(N)
plt.show()Needs pandas, numpy, matplotlib · reads ngram-bars-demo.csv · app theme from the optional codesplash helper
# Top terms — Codesplash Chart Lab (recipe "ngram-bars")
# controls: top=20
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("ngram-bars-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["rating"] = pd.Categorical(df["rating"].astype("string"), categories=["1–2 stars", "4–5 stars"])
TERM = "bigram"
N = "count"
G = "rating"
TOP = 20
keys = [TERM] + ([G] if G else [])
d = df.groupby(keys, observed=True)[N].sum().reset_index()
d = d.sort_values(N, ascending=False).groupby(G, observed=True).head(TOP) if G else d.sort_values(N, ascending=False).head(TOP)
fig = px.bar(d.iloc[::-1], x=N, y=TERM, orientation="h", facet_col=G, color=G, color_discrete_sequence=PALETTE)
fig.update_yaxes(matches=None, showticklabels=True)
fig.update_layout(showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads ngram-bars-demo.csv · app theme from the optional codesplash helper
# Top terms — Codesplash Chart Lab (recipe "ngram-bars")
# controls: top=20
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("ngram-bars-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["bigram"]] <- factor(df[["bigram"]])
df[["rating"]] <- factor(df[["rating"]], levels = c("1–2 stars", "4–5 stars"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
term_col <- "bigram"
n_col <- "count"
g_col <- "rating"
top_n <- 20
d <- data.frame(term = as.character(df[[term_col]]), n = df[[n_col]], g = if (is.null(g_col)) "" else as.character(df[[g_col]]))
d <- stats::aggregate(n ~ g + term, data = d, FUN = sum)
d <- do.call(rbind, lapply(split(d, d$g), function(x) utils::head(x[order(-x$n, x$term), ], top_n)))
d$g <- factor(d$g, levels = if (is.null(g_col)) "" else levels_of(df[[g_col]]))
d$key <- factor(paste(d$g, d$term, sep = "\r"), levels = rev(paste(d$g, d$term, sep = "\r")))
p <- ggplot(d, aes(n, key, fill = g)) + geom_col() + facet_wrap(~g, scales = "free_y") +
scale_y_discrete(labels = function(k) sub(".*\r", "", k)) + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = n_col, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads ngram-bars-demo.csv · app theme from the optional codesplashr helper