svgconfidence-ellipse
Confidence and data ellipses
Where do two variables' means sit, how precisely, and do the groups' clouds differ in shape?
How to read it
- Read points as rows, colour as group.
- Small ellipses: the region for each group's mean. Larger ones: where most rows lie.
- Means whose ellipses don't overlap are well apart.
- Callout 1: The ellipse around one group's mean.
- Callout 2: Tilt: how the two variables move together inside the group.
- Callout 3: Group colours and sizes.
Watch out
- Ellipses assume near-normal data, and comparing two variables hides what happens on the others.
Defaults
- Ellipse
- Confidence ellipse of the mean
- The mean's confidence region shrinks with n; the data ellipse shows the spread and correlation of the rows (compare shapes for Box's M).
- Also: Data ellipse (covariance)
- Level
- 0.95
- Coverage of the ellipse (0.68 ≈ one standard deviation for data ellipses).
- Range 0.5 to 0.999, step 0.01
- Show the rows
- On
- Draw every row as well as the ellipses.
Pinned in the code
- Each group's mean and covariance use the n − 1 denominator; ellipse axes come from the covariance's eigen decomposition.
- Confidence ellipse of the mean: (x̄ − μ)' S⁻¹ (x̄ − μ) ≤ 2(n − 1) F₂,ₙ₋₂(level) / (n(n − 2)) — Hotelling's exact region for two variables.
- Data ellipse: (x − x̄)' S⁻¹ (x − x̄) ≤ χ²₂(level), covering `level` of a bivariate normal population; at 68% it is the one-standard-deviation contour.
- Two means whose confidence ellipses do not overlap differ in the joint test, but overlapping ellipses do not prove equality (as with univariate intervals).
# Confidence and data ellipses — Codesplash Chart Lab (recipe "confidence-ellipse")
# controls: kind=mean, level=0.95, points=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("confidence-ellipse-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica"])
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 ellipse(xy, kind, level):
"""data: radius √χ²₂(level). mean: Hotelling's region, √[2(n−1)F₂,ₙ₋₂(level) / (n(n−2))]."""
n, m = len(xy), xy.mean(axis=0)
if n <= 2:
return np.empty((0, 2)), m
c = np.sqrt(stats.chi2.ppf(level, 2)) if kind == "data" else np.sqrt(2 * (n - 1) * stats.f.ppf(level, 2, n - 2) / (n * (n - 2)))
vals, vecs = np.linalg.eigh(np.cov(xy.T))
t = np.linspace(0, 2 * np.pi, 73)
return m + (c * vecs @ (np.sqrt(np.maximum(vals, 0))[:, None] * np.vstack([np.cos(t), np.sin(t)]))).T, m
X = "petal length (cm)"
Y = "petal width (cm)"
G = "species"
d = df.dropna(subset=[X, Y] + ([G] if G else []))
fig, ax = plt.subplots(figsize=(7, 5))
ks = levels_of(d[G]) if G else ["all rows"]
many = len(ks) > 1 # several groups: marker shape and ellipse dash per group, as in the app
for i, k in enumerate(ks):
xy = (d[d[G].astype(str) == str(k)] if G else d)[[X, Y]].to_numpy(float)
col = PALETTE[i % len(PALETTE)]
ax.scatter(xy[:, 0], xy[:, 1], s=12, color=col, alpha=0.45, marker=SERIES_MARKERS[i % 8] if many else "o")
path, m = ellipse(xy, "mean", 0.95)
ax.plot(path[:, 0], path[:, 1], color=col, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if many else "-", label=f"{k} (n = {len(xy)})")
ax.scatter([m[0]], [m[1]], marker="+", s=60, color=col)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads confidence-ellipse-demo.csv · app theme from the optional codesplash helper
# Confidence and data ellipses — Codesplash Chart Lab (recipe "confidence-ellipse")
# controls: kind=mean, level=0.95, points=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("confidence-ellipse-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica"])
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 ellipse(xy, kind, level):
"""data: radius √χ²₂(level). mean: Hotelling's region, √[2(n−1)F₂,ₙ₋₂(level) / (n(n−2))]."""
n, m = len(xy), xy.mean(axis=0)
if n <= 2:
return np.empty((0, 2)), m
c = np.sqrt(stats.chi2.ppf(level, 2)) if kind == "data" else np.sqrt(2 * (n - 1) * stats.f.ppf(level, 2, n - 2) / (n * (n - 2)))
vals, vecs = np.linalg.eigh(np.cov(xy.T))
t = np.linspace(0, 2 * np.pi, 73)
return m + (c * vecs @ (np.sqrt(np.maximum(vals, 0))[:, None] * np.vstack([np.cos(t), np.sin(t)]))).T, m
X = "petal length (cm)"
Y = "petal width (cm)"
G = "species"
d = df.dropna(subset=[X, Y] + ([G] if G else []))
fig = go.Figure()
ks = levels_of(d[G]) if G else ["all rows"]
many = len(ks) > 1 # several groups: marker shape and ellipse dash per group, as in the app
for i, k in enumerate(ks):
xy = (d[d[G].astype(str) == str(k)] if G else d)[[X, Y]].to_numpy(float)
col = PALETTE[i % len(PALETTE)]
fig.add_scatter(x=xy[:, 0], y=xy[:, 1], mode="markers", marker=dict(color=col, size=6, opacity=0.45, symbol=SERIES_MARKERS[i % 8] if many else "circle"), showlegend=False)
path, m = ellipse(xy, "mean", 0.95)
fig.add_scatter(x=path[:, 0], y=path[:, 1], mode="lines", line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if many else "solid"), name=f"{k} (n = {len(xy)})")
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly, scipy · reads confidence-ellipse-demo.csv · app theme from the optional codesplash helper
# Confidence and data ellipses — Codesplash Chart Lab (recipe "confidence-ellipse")
# controls: kind=mean, level=0.95, points=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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("confidence-ellipse-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "petal length (cm)"
Y <- "petal width (cm)"
G <- "species"
ellipse <- function(x, y, kind, level) { # data: √χ²₂(level); mean: Hotelling's region
n <- length(x)
if (n <= 2) return(NULL)
r <- if (kind == "data") sqrt(qchisq(level, 2)) else sqrt(2 * (n - 1) * qf(level, 2, n - 2) / (n * (n - 2)))
e <- eigen(cov(cbind(x, y)), symmetric = TRUE)
t <- seq(0, 2 * pi, length.out = 73)
p <- r * e$vectors %*% (sqrt(pmax(e$values, 0)) * rbind(cos(t), sin(t)))
data.frame(x = mean(x) + p[1, ], y = mean(y) + p[2, ])
}
d <- df[complete.cases(df[, c(X, Y, G)]), ]
d$.x <- d[[X]]; d$.y <- d[[Y]]
d$.g <- if (is.null(G)) factor("all rows") else factor(as.character(d[[G]]), levels = levels_of(d[[G]]))
paths <- do.call(rbind, lapply(levels(d$.g), function(k) {
e <- ellipse(d$.x[d$.g == k], d$.y[d$.g == k], "mean", 0.95)
if (is.null(e)) return(NULL)
e$.g <- k; e
}))
p <- ggplot() +
geom_point(aes(.x, .y, colour = .g, shape = .g), d, size = 1.2, alpha = 0.45) +
geom_path(aes(x, y, colour = .g, linetype = .g), paths, linewidth = 0.9) + # shape and dash per group, as in the app
scale_colour_manual(values = cs_cat, name = NULL) + scale_linetype_manual(values = cs_linetypes, name = NULL) +
scale_shape_manual(values = cs_shapes, name = NULL) +
labs(x = X, y = Y) + theme_cs
print(p)Needs ggplot2 · reads confidence-ellipse-demo.csv · app theme from the optional codesplashr helper