Sign in

MANOVA

Multivariate Analysis of Variance

A test of whether groups differ on several outcome variables at once, comparing between-group and within-group scatter matrices.

Overview

ANOVA compares groups on one outcome. With several outcomes you could run one ANOVA per outcome, but that multiplies the chance of a false alarm and ignores how the outcomes move together. MANOVA (multivariate analysis of variance) treats each observation as a vector. The sums of squares become matrices: HH holds the scatter of the group mean vectors around the grand mean, and EE holds the scatter of observations around their own group mean. The test asks whether HH is large relative to EE in any direction. Groups that overlap on every single outcome can still separate clearly along a combination of them, and MANOVA can see that.

A short history

MANOVA extends Fisher's analysis of variance to several outcomes at once. Harold Hotelling published the two group case, the T squared statistic, in 1931, and Samuel Wilks introduced the lambda criterion for several groups in 1932. Later statistics by Lawley, Hotelling, Roy and K. C. S. Pillai offer different trade offs, and Pillai's trace from 1955 is valued for its robustness. Testing the outcomes jointly controls the false alarm rate and uses their correlations.

How it works

  1. Stack each group as an array of shape (ni,p)(n_i, p) and compute its mean vector and the grand mean vector.
  2. Build HH by adding, for each group, nin_i times the outer product of its mean's offset from the grand mean.
  3. Build EE by adding the outer products of every observation's offset from its own group mean.
  4. Compute the eigenvalues of E−1HE^{-1}H. Each one is a between-to-within ratio along one direction.
  5. Combine the eigenvalues into the four classic statistics: Wilks, Pillai, Hotelling-Lawley and Roy.
  6. Convert each statistic to an FF value and a p-value. The configured statistic decides reject.

Watch out for

  • A significant result says that the mean vectors differ, not on which outcome, so follow up with single-outcome tests or by inspecting the leading direction.
  • The test assumes every group has the same covariance matrix. Unequal covariances with unequal group sizes distort the p-values, and Pillai's trace is the most robust of the four.
  • EE must be invertible, which needs more error degrees of freedom than outcomes. With many outcomes and few observations the test has little power or cannot run.
  • The FF values are approximations outside a few exact cases, and Roy's is an upper bound, so its p-value is a lower bound and too optimistic.

Use cases

When to use it

Comparing groups on several related numeric outcomes measured on the same subjects, when you want one overall test that respects the correlation between the outcomes.

In industry

Psychology
Researchers compare therapy groups on several related scores, such as anxiety, mood and sleep, in one test before looking at each score.
Agriculture and biology
Field trials compare plant varieties on yield, height and protein content together, since these traits are correlated.
Product testing
Sensory panels rate products on several attributes, and a single multivariate test checks whether the products differ at all.

Choosing it: what must hold

  • Two or more numeric outcomes that are moderately correlated and measured on every subject.
  • Independent observations with more subjects in each group than there are outcomes.
  • Outcomes that are roughly multivariate normal within groups, with similar covariance matrices.
  • No outcome that is nearly a linear combination of the others.

When to choose something else

IfUse instead
There is only one outcomeOne-way ANOVA or two-way ANOVA
Outcomes are uncorrelated or you care about each one separatelySeparate ANOVAs with a Bonferroni correction
Normality or equal covariance clearly failsA permutation based test such as PERMANOVA

Math foundations

  1. The hypotheses

    H0: μ1=μ2=⋯=μgH_0:\ \boldsymbol{\mu}_1 = \boldsymbol{\mu}_2 = \cdots = \boldsymbol{\mu}_g

    Each μi\boldsymbol{\mu}_i is a vector of pp population means, one per outcome. The null hypothesis says the groups agree on all of them at once.

  2. Between-group scatter

    H=∑i=1gni (yˉi−yˉ)(yˉi−yˉ)⊤H = \sum_{i=1}^{g} n_i\,(\bar{\mathbf{y}}_i-\bar{\mathbf{y}})(\bar{\mathbf{y}}_i-\bar{\mathbf{y}})^{\top}

    The matrix version of the between-group sum of squares. Its diagonal holds the ordinary SSBSS_B of each outcome and its off-diagonal entries record how the group means move together.

  3. Within-group scatter

    E=∑i=1g∑j=1ni(yij−yˉi)(yij−yˉi)⊤E = \sum_{i=1}^{g}\sum_{j=1}^{n_i}(\mathbf{y}_{ij}-\bar{\mathbf{y}}_i)(\mathbf{y}_{ij}-\bar{\mathbf{y}}_i)^{\top}

    The matrix version of the within-group sum of squares. It measures noise, including the correlation between outcomes inside a group.

  4. Eigenvalues

    E−1H vm=λmvm,λ1≥λ2≥⋯≥λs≥0,s=min⁡(p, g−1)E^{-1}H\,\mathbf{v}_m = \lambda_m \mathbf{v}_m, \qquad \lambda_1 \ge \lambda_2 \ge \cdots \ge \lambda_s \ge 0, \quad s = \min(p,\ g-1)

    Each λm\lambda_m is the between-to-within ratio along the direction vm\mathbf{v}_m. They play the role of SSB/SSWSS_B/SS_W, one per independent direction in which groups can differ.

  5. Wilks' lambda

    Λ=det⁡Edet⁡(H+E)=∏m=1s11+λm\Lambda = \frac{\det E}{\det(H+E)} = \prod_{m=1}^{s}\frac{1}{1+\lambda_m}

    The share of the generalised variance that is not explained by the groups. It lies between 0 and 1, and small values are evidence against the null hypothesis.

  6. The other three statistics

    V=∑m=1sλm1+λm,U=∑m=1sλm,θ=λ1V = \sum_{m=1}^{s}\frac{\lambda_m}{1+\lambda_m}, \qquad U = \sum_{m=1}^{s}\lambda_m, \qquad \theta = \lambda_1

    Pillai's trace VV, the Hotelling-Lawley trace UU and Roy's largest root as the template reports it. They weight the eigenvalues differently, so they agree when one direction dominates and can disagree when the difference is spread over several.

Symbols

gg
number of groups
pp
number of outcome variables
nin_i
number of observations in group i
yij\mathbf{y}_{ij}
outcome vector of observation j in group i
yˉi, yˉ\bar{\mathbf{y}}_i,\ \bar{\mathbf{y}}
mean vector of group i and grand mean vector
μi\boldsymbol{\mu}_i
population mean vector of group i
H, EH,\ E
between-group and within-group scatter matrices, both p by p
λm, vm\lambda_m,\ \mathbf{v}_m
eigenvalue m of the matrix product and its direction
Λ, V, U, θ\Lambda,\ V,\ U,\ \theta
Wilks' lambda, Pillai's trace, Hotelling-Lawley trace, Roy's largest root

Worked by hand

Take two outcomes with E=(8004)E = \begin{pmatrix} 8 & 0 \\ 0 & 4 \end{pmatrix} and H=(8001)H = \begin{pmatrix} 8 & 0 \\ 0 & 1 \end{pmatrix}. Both are diagonal, so the eigenvalues of E−1HE^{-1}H are the ratios of the diagonal entries.

λ1=88=1,λ2=14=0.25\lambda_1 = \frac{8}{8} = 1, \qquad \lambda_2 = \frac{1}{4} = 0.25
Λ=11+1⋅11+0.25=0.5×0.8=0.4\Lambda = \frac{1}{1+1}\cdot\frac{1}{1+0.25} = 0.5 \times 0.8 = 0.4
det⁡Edet⁡(H+E)=8⋅416⋅5=3280=0.4\frac{\det E}{\det(H+E)} = \frac{8\cdot 4}{16\cdot 5} = \frac{32}{80} = 0.4
V=12+0.251.25=0.7,U=1+0.25=1.25,θ=1V = \frac{1}{2}+\frac{0.25}{1.25} = 0.7, \qquad U = 1 + 0.25 = 1.25, \qquad \theta = 1

Both routes give Λ=0.4\Lambda = 0.4: 60% of the generalised variance is tied to the groups. The first outcome carries most of the separation, which is why Roy's root is 1 while the second eigenvalue adds little.

Visual example

Loading the example.

Try this

  • Turn the direction to 45 degrees: the shift now runs along the clouds and the multivariate test loses its advantage.
  • Set the correlation to 0 and compare the three p-values again.
  • Raise the size of the shift until both single outcomes become significant too.

Code sample

import numpy as np
from impl import Manova
from config import ManovaConfig

rng = np.random.default_rng(0)
groups = [rng.normal(size=(15, 3)) + 0.6 * i for i in range(3)]   # 3 groups, 3 outcomes
result = Manova(ManovaConfig(statistic="wilks")).fit(groups)
print(result["wilks"]["value"], result["wilks"]["f"], result["p_value"], result["reject"])
Read the implementation (145 lines)
"""MANOVA: one-way multivariate analysis of variance with the four classic test statistics.

NumPy and the standard library only. The F tail probability comes from the regularized incomplete beta
function defined in this file.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import ManovaConfig
except ImportError:  # run from the template's own folder
    from config import ManovaConfig

def _betacf(a: float, b: float, x: float) -> float:
    """Continued fraction of the incomplete beta function (modified Lentz method)."""
    tiny = 1e-300
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    d = 1.0 / (d if abs(d) > tiny else tiny)
    h = d
    for m in range(1, 2000):
        m2 = 2 * m
        for aa in (
            m * (b - m) * x / ((qam + m2) * (a + m2)),
            -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
        ):
            d = 1.0 + aa * d
            d = 1.0 / (d if abs(d) > tiny else tiny)
            c = 1.0 + aa / c
            c = c if abs(c) > tiny else tiny
            delta = d * c
            h *= delta
        if abs(delta - 1.0) < 1e-15:
            break
    return h


def betainc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        return front * _betacf(a, b, x) / a
    return 1.0 - front * _betacf(b, a, 1.0 - x) / b

def f_sf(f: float, df1: float, df2: float) -> float:
    """P(F > f) for an F variable with (`df1`, `df2`) degrees of freedom."""
    if f <= 0.0:
        return 1.0
    return betainc(0.5 * df2, 0.5 * df1, df2 / (df2 + df1 * f))


def f_cdf(f: float, df1: float, df2: float) -> float:
    """P(F <= f) for an F variable with (`df1`, `df2`) degrees of freedom."""
    return 1.0 - f_sf(f, df1, df2)

class Manova:
    """Compares the between-group scatter matrix H with the within-group scatter matrix E."""

    def __init__(self, config: ManovaConfig | None = None) -> None:
        self.config = config or ManovaConfig()

    @staticmethod
    def scatter_matrices(groups) -> tuple[np.ndarray, np.ndarray]:
        """Between-group (H) and within-group (E) sums of squares and cross products, both (p, p).

        groups: a sequence of arrays of shape (n_i, p).
        """
        samples = [np.asarray(g, dtype=float) for g in groups]
        grand = np.vstack(samples).mean(axis=0)
        p = grand.size
        h, e = np.zeros((p, p)), np.zeros((p, p))
        for s in samples:
            centre = s.mean(axis=0)
            h += s.shape[0] * np.outer(centre - grand, centre - grand)
            e += (s - centre).T @ (s - centre)
        return h, e

    def fit(self, groups) -> dict:
        """Run the test.

        groups: a sequence of g >= 2 arrays of shape (n_i, p): n_i observations of p outcome variables.
                A 1-D array is read as one variable (p = 1).
        Returns a dict with `H`, `E` (p, p), `eigenvalues` of inv(E) H (largest first), and one entry per
        statistic (`wilks`, `pillai`, `hotelling_lawley`, `roy`), each holding `value`, `f`, `df1`, `df2`,
        `p_value`. `p_value` and `reject` at the top level belong to the configured statistic.
        The F values are exact for Wilks when p <= 2 or g <= 3, exact for all four when g = 2, and
        approximations otherwise. Roy's F is an upper bound, so its p-value is a lower bound.
        """
        samples = [np.asarray(g, dtype=float) for g in groups]
        samples = [s.reshape(-1, 1) if s.ndim == 1 else s for s in samples]
        if len(samples) < 2:
            raise ValueError("need at least 2 groups")
        p = samples[0].shape[1]
        if any(s.ndim != 2 or s.shape[1] != p for s in samples):
            raise ValueError("every group must have shape (n_i, p) with the same p")
        n_total, g = sum(s.shape[0] for s in samples), len(samples)
        q, df_error = g - 1, n_total - g  # hypothesis and error degrees of freedom
        if df_error < p:
            raise ValueError("need at least p more observations than groups")
        h, e = self.scatter_matrices(samples)
        eig = np.sort(np.clip(np.linalg.eigvals(np.linalg.solve(e, h)).real, 0.0, None))[::-1]
        s = min(p, q)
        eig_s = eig[:s]  # the other eigenvalues are zero
        m = (abs(p - q) - 1) / 2.0
        n = (df_error - p - 1) / 2.0

        wilks = float(np.prod(1.0 / (1.0 + eig_s)))
        denom = p * p + q * q - 5
        t = math.sqrt((p * p * q * q - 4) / denom) if denom > 0 else 1.0
        df1 = float(p * q)
        df2 = (df_error + q - (p + q + 1) / 2.0) * t - (p * q - 2) / 2.0
        root = wilks ** (1.0 / t)
        stats = {"wilks": self._entry(wilks, (1.0 - root) / root * df2 / df1, df1, df2)}

        pillai = float(np.sum(eig_s / (1.0 + eig_s)))
        df1, df2 = s * (2 * m + s + 1), s * (2 * n + s + 1)
        stats["pillai"] = self._entry(pillai, pillai / (s - pillai) * df2 / df1, df1, df2)

        trace = float(np.sum(eig_s))
        df1, df2 = s * (2 * m + s + 1), 2 * (s * n + 1)
        stats["hotelling_lawley"] = self._entry(trace, trace * df2 / (s * df1), df1, df2)

        d = max(p, q)
        df1, df2 = float(d), float(df_error - d + q)
        stats["roy"] = self._entry(float(eig_s[0]), float(eig_s[0]) * df2 / df1, df1, df2)

        chosen = stats[self.config.statistic]
        return {"H": h, "E": e, "eigenvalues": eig, **stats,
                "p_value": chosen["p_value"], "reject": chosen["p_value"] < self.config.alpha}

    @staticmethod
    def _entry(value: float, f: float, df1: float, df2: float) -> dict:
        """One row of the result: the statistic, its F approximation and the p-value."""
        return {"value": value, "f": float(f), "df1": float(df1), "df2": float(df2),
                "p_value": f_sf(float(f), df1, df2)}
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Generate three groups of 20 two-dimensional points with means (0,0)(0,0), (1,1)(1,1) and (2,2)(2,2) and correlated noise. Call Manova().fit(groups) and read eigenvalues and the four statistics. Use Manova.scatter_matrices(groups) to get H and E and confirm that wilks equals det⁡E/det⁡(H+E)\det E / \det(H+E).

Check on learning

  1. Two groups overlap heavily on outcome 1 and on outcome 2 when each is viewed alone, yet MANOVA rejects strongly. Sketch a data picture in which this happens.
    A way to think about it

    Think of two long, thin, parallel clouds of points lying along a diagonal. Project them onto each axis, then onto the direction across the clouds.

  2. With three groups whose mean vectors lie on one straight line, how many eigenvalues do you expect to be clearly above zero, and which statistic uses that fact best?
    A way to think about it

    The eigenvalues count independent directions of separation. Compare a statistic that looks only at the largest with ones that sum over all.

  3. Why does running pp separate ANOVAs at level α\alpha not control the error rate the way one MANOVA does?
    A way to think about it

    Work out the chance of at least one false rejection across several tests, then consider that correlated outcomes make the tests overlap in what they detect.

  4. What happens to EE when you have 10 outcomes but only 8 error degrees of freedom, and why does the template raise an error in that case?
    A way to think about it

    A sum of 8 independent outer products can have rank at most 8. Ask whether a 10 by 10 matrix of rank 8 can be inverted.