svganomaly-scores
Anomaly score distribution
How unusual are the most anomalous rows compared with the rest, and where is the cut?
How to read it
- Read the histogram as all rows' anomaly scores.
- Find the dashed threshold: rows beyond it are flagged in red.
- A clear gap before the threshold is reassuring; a smooth tail means the cut is arbitrary.
- Callout 1: Most rows: low scores.
- Callout 2: Threshold: the flagging cut.
- Callout 3: Flagged rows.
Watch out
- An anomaly isn't an error or a fraud. Investigate each flag.
Defaults
- Threshold (0 = smallest flagged score)
- 0
- The score above which rows are flagged.
- Range -1,000,000,000 to 1,000,000,000, step 0.01
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.
- Scores are oriented so higher = more anomalous (the run converts scikit-learn's negative outlier factor and isotree's depth-based scores to that convention).
- Bins: about 1.5 √n, between 10 and 60. Without an explicit threshold the line sits at the smallest flagged score (the contamination cut the run used).
# Anomaly score distribution — Codesplash Chart Lab (recipe "anomaly-scores")
# controls: threshold=0
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("anomaly-scores-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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 truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
S = "anomaly score"
FLAG = "flagged"
THRESHOLD = 0 # 0 = the smallest flagged score
d = df.dropna(subset=[S])
flag = truthy(d[FLAG]) if FLAG else pd.Series(False, index=d.index)
k = int(min(60, max(10, round(1.5 * np.sqrt(len(d)))))) # about 1.5 √n bins
edges = np.linspace(d[S].min(), d[S].max(), k + 1)
normal, _ = np.histogram(d.loc[~flag, S], bins=edges)
flagged, _ = np.histogram(d.loc[flag, S], bins=edges)
thr = THRESHOLD if THRESHOLD != 0 else (d.loc[flag, S].min() if flag.any() else None)
fig, ax = plt.subplots(figsize=(8, 4.5))
w = np.diff(edges)
ax.bar(edges[:-1], normal, width=w, align="edge", color=PALETTE[0], label="normal")
ax.bar(edges[:-1], flagged, width=w, align="edge", bottom=normal, color="#ce5342", label="flagged")
if thr is not None:
ax.axvline(thr, color=REF, linestyle="--", linewidth=1.2, label=f"threshold {thr:.3g}")
ax.set_xlabel(S)
ax.set_ylabel("rows")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads anomaly-scores-demo.csv · app theme from the optional codesplash helper
# Anomaly score distribution — Codesplash Chart Lab (recipe "anomaly-scores")
# controls: threshold=0
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("anomaly-scores-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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 truthy(s):
return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
S = "anomaly score"
FLAG = "flagged"
THRESHOLD = 0
d = df.dropna(subset=[S])
flag = truthy(d[FLAG]) if FLAG else pd.Series(False, index=d.index)
k = int(min(60, max(10, round(1.5 * np.sqrt(len(d))))))
edges = np.linspace(d[S].min(), d[S].max(), k + 1)
normal, _ = np.histogram(d.loc[~flag, S], bins=edges)
flagged, _ = np.histogram(d.loc[flag, S], bins=edges)
mid, w = (edges[:-1] + edges[1:]) / 2, np.diff(edges)
thr = THRESHOLD if THRESHOLD != 0 else (float(d.loc[flag, S].min()) if flag.any() else None)
fig = go.Figure()
fig.add_bar(x=mid, y=normal, width=w, name="normal", marker_color=PALETTE[0])
fig.add_bar(x=mid, y=flagged, width=w, name="flagged", marker_color="#ce5342")
if thr is not None:
fig.add_vline(x=thr, line=dict(color=REF, dash="dash", width=1.2), annotation_text=f"threshold {thr:.3g}")
fig.update_layout(barmode="stack", bargap=0, xaxis_title=S, yaxis_title="rows")
fig.show()Needs pandas, numpy, plotly · reads anomaly-scores-demo.csv · app theme from the optional codesplash helper
# Anomaly score distribution — Codesplash Chart Lab (recipe "anomaly-scores")
# controls: threshold=0
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("anomaly-scores-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["flagged"]] <- as.logical(df[["flagged"]])
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
truthy <- function(v) tolower(trimws(as.character(v))) %in% c("true", "1", "yes", "t")
s_col <- "anomaly score"
flag_col <- "flagged"
threshold <- 0 # 0 = the smallest flagged score
d <- data.frame(s = df[[s_col]], flag = if (is.null(flag_col)) FALSE else truthy(df[[flag_col]]))
d <- d[!is.na(d$s), ]
k <- min(60, max(10, round(1.5 * sqrt(nrow(d))))) # about 1.5 sqrt(n) bins
edges <- seq(min(d$s), max(d$s), length.out = k + 1)
d$group <- factor(ifelse(d$flag, "flagged", "normal"), levels = c("flagged", "normal"))
thr <- if (threshold != 0) threshold else if (any(d$flag)) min(d$s[d$flag]) else NA
p <- ggplot(d, aes(s, fill = group)) + geom_histogram(breaks = edges, position = "stack", colour = NA) +
{ if (!is.na(thr)) geom_vline(xintercept = thr, linetype = "dashed", colour = ref_col) } +
scale_fill_manual(values = c(normal = cs_cat[1], flagged = "#ce5342")) + labs(x = s_col, y = "rows", fill = NULL) + theme_cs
print(p)Needs ggplot2 · reads anomaly-scores-demo.csv · app theme from the optional codesplashr helper