Skip to content
svgconfidence-ellipse

Confidence and data ellipses

Where do two variables' means sit, how precisely, and do the groups' clouds differ in shape?

Demo data · seed 20261101 · 150 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read points as rows, colour as group.
  2. Small ellipses: the region for each group's mean. Larger ones: where most rows lie.
  3. Means whose ellipses don't overlap are well apart.
  1. Callout 1: The ellipse around one group's mean.
  2. Callout 2: Tilt: how the two variables move together inside the group.
  3. 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