svgembedding-map
Category embedding map
Which levels of a categorical variable does the model treat as alike?
How to read it
- Read each dot as one level of a categorical feature, placed by the vector the network learned for it.
- Levels close together act alike on the target; a level far from the rest gets treated differently.
- Compare levels within one colour (one feature): distances between features' levels are not comparable.
- Callout 1: Two levels the model treats alike: close together.
- Callout 2: A level set apart from the rest.
- Callout 3: The dashed zero lines: the centre of each feature's levels.
Watch out
- The axes have no meaning: any rotation of an embedding fits equally well, so read distances and neighbours only.
- A small dot (a rare level) keeps a vector near its random start; its position says little.
- Two principal components show only part of the distances when the vectors have more dimensions; check the nearest-level table.
Defaults
- Label levels
- On
- Names next to the dots; labels that would overlap are left out (hover shows every level).
- Equal axis units
- On
- One unit has the same length on both axes, so distances on the map are comparable in every direction.
Pinned in the code
- Draws the coordinates the Python or R engine computed; the chart computes nothing statistical.
- Coordinates are each feature's level vectors projected on their first two principal components (centred; each component's sign fixed so its largest loading is positive). Two components show only part of the distances when vectors have more dimensions.
- Read distances and neighbours, not axes: any rotation of an embedding fits the data equally well.
- Dot area grows with the level's row count (√ scaling, 3–9 px); rare levels keep vectors near their random start, so their positions mean little.
# Category embedding map — Codesplash Chart Lab (recipe "embedding-map")
# controls: labels=true, equal=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("embedding-map-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["weekday", "store type"])
_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 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)))
def dot_px(sizes):
"""Dot radius as in the app: 3 + 6·√(rows / max rows) px, 4 px without rows."""
s = np.asarray(sizes, dtype=float)
top = np.nanmax(s) if np.isfinite(s).any() and np.nanmax(s) > 0 else 0
return np.where(np.isfinite(s) & (s > 0) & (top > 0), 3 + 6 * np.sqrt(np.clip(s, 0, None) / (top or 1)), 4.0)
X = "PC 1"
Y = "PC 2"
LABEL = "level"
G = "feature"
SIZE = "rows"
LABELS, EQUAL = True, True
d = df.dropna(subset=[X, Y]).reset_index(drop=True)
groups = levels_of(d[G]) if G else [None]
r = dot_px(d[SIZE] if SIZE else np.full(len(d), np.nan))
fig, ax = plt.subplots(figsize=(7, 6))
ax.axhline(0, color=REF, alpha=0.35, linestyle="--", linewidth=0.8)
ax.axvline(0, color=REF, alpha=0.35, linestyle="--", linewidth=0.8)
for i, k in enumerate(groups):
m = (d[G].astype(str) == str(k)).to_numpy() if G else np.ones(len(d), bool)
ax.scatter(d.loc[m, X], d.loc[m, Y], s=(r[m] * 1.4) ** 2, color=PALETTE[i % len(PALETTE)], alpha=0.72, edgecolors="white", linewidths=0.8, label=k)
if LABELS and LABEL:
for _, row in d.iterrows(): # every level is labelled; the app skips labels that would overlap
ax.annotate(str(row[LABEL]), (row[X], row[Y]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
if EQUAL:
ax.set_aspect("equal", adjustable="datalim") # equal units: distances read the same both ways
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
ax.legend(title=G, fontsize=8)
ax.set_title("Learned category embeddings: close levels act alike on the target")
plt.show()Needs pandas, numpy, matplotlib · reads embedding-map-demo.csv · app theme from the optional codesplash helper
# Category embedding map — Codesplash Chart Lab (recipe "embedding-map")
# controls: labels=true, equal=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("embedding-map-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["weekday", "store type"])
_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 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)))
def dot_px(sizes):
"""Dot radius as in the app: 3 + 6·√(rows / max rows) px, 4 px without rows."""
s = np.asarray(sizes, dtype=float)
top = np.nanmax(s) if np.isfinite(s).any() and np.nanmax(s) > 0 else 0
return np.where(np.isfinite(s) & (s > 0) & (top > 0), 3 + 6 * np.sqrt(np.clip(s, 0, None) / (top or 1)), 4.0)
X = "PC 1"
Y = "PC 2"
LABEL = "level"
G = "feature"
SIZE = "rows"
LABELS, EQUAL = True, True
d = df.dropna(subset=[X, Y]).reset_index(drop=True)
groups = levels_of(d[G]) if G else [None]
r = dot_px(d[SIZE] if SIZE else np.full(len(d), np.nan))
fig = go.Figure()
for i, k in enumerate(groups):
m = (d[G].astype(str) == str(k)).to_numpy() if G else np.ones(len(d), bool)
text = d.loc[m, LABEL].astype(str) if LABEL else None
fig.add_scatter(
x=d.loc[m, X], y=d.loc[m, Y], mode="markers+text" if (LABELS and LABEL) else "markers", text=text,
textposition="middle right", name=str(k) if k is not None else "levels",
marker=dict(size=2 * r[m], color=PALETTE[i % len(PALETTE)], opacity=0.72, line=dict(color="white", width=1)),
)
fig.add_hline(y=0, line_dash="dash", line_color=REF, opacity=0.35)
fig.add_vline(x=0, line_dash="dash", line_color=REF, opacity=0.35)
fig.update_layout(xaxis_title=X, yaxis_title=Y, legend_title_text=G or "", title="Learned category embeddings")
if EQUAL:
fig.update_yaxes(scaleanchor="x", scaleratio=1) # equal units
fig.show()Needs pandas, numpy, plotly · reads embedding-map-demo.csv · app theme from the optional codesplash helper
# Category embedding map — Codesplash Chart Lab (recipe "embedding-map")
# controls: labels=true, equal=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("embedding-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["level"]] <- factor(df[["level"]])
df[["feature"]] <- factor(df[["feature"]], levels = c("weekday", "store type"))
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
x_col <- "PC 1"
y_col <- "PC 2"
label_col <- "level"
g_col <- "feature"
size_col <- "rows"
show_labels <- TRUE; equal_units <- TRUE
keep <- !is.na(df[[x_col]]) & !is.na(df[[y_col]])
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
ks <- if (is.null(g_col)) "levels" else levels_of(df[[g_col]][keep])
d <- data.frame(x = df[[x_col]][keep], y = df[[y_col]][keep],
k = factor(if (is.null(g_col)) "levels" else as.character(df[[g_col]][keep]), levels = ks),
lab = if (is.null(label_col)) "" else as.character(df[[label_col]][keep]),
n = if (is.null(size_col)) NA_real_ else df[[size_col]][keep])
top <- suppressWarnings(max(d$n[is.finite(d$n) & d$n > 0]))
d$r <- ifelse(is.finite(d$n) & d$n > 0 & is.finite(top), 3 + 6 * sqrt(pmax(d$n, 0) / top), 4) # px, as the app
p <- ggplot(d, aes(x, y, colour = k)) +
geom_hline(yintercept = 0, colour = ref_col, alpha = 0.35, linetype = "dashed") +
geom_vline(xintercept = 0, colour = ref_col, alpha = 0.35, linetype = "dashed") +
geom_point(aes(size = r), alpha = 0.72) +
{ if (show_labels && !is.null(label_col)) geom_text(aes(label = lab), hjust = -0.25, size = 3, show.legend = FALSE) } +
scale_size_identity() +
scale_colour_manual(values = setNames(rep_len(cs_cat, length(ks)), ks)) +
{ if (equal_units) coord_equal() } + # equal units: distances read the same both ways
labs(x = x_col, y = y_col, colour = g_col, title = "Learned category embeddings") + theme_cs
print(p)Needs ggplot2 · reads embedding-map-demo.csv · app theme from the optional codesplashr helper
- Every level is labelled here; the app leaves out labels that would overlap (hover shows them all).