matplotlib/matplotlib · error · ValueError

alpha is array-like but its shape {alpha.shape} does not mat

Error message

alpha is array-like but its shape {alpha.shape} does not match that of X {xa.shape}

What it means

When a Colormap is called with an array-like alpha (cmap(X, alpha=...)), the alpha must be a scalar or an array whose shape exactly equals the shape of the normalized data X. Any other shape is rejected before the alpha channel is written into the RGBA output.

Source

Thrown at lib/matplotlib/colors.py:851

        with np.errstate(invalid="ignore"):
            # We need this cast for unsigned ints as well as floats
            xa = xa.astype(int)
        xa[mask_under] = self._i_under
        xa[mask_over] = self._i_over
        xa[mask_bad] = self._i_bad

        lut = self._lut
        if bytes:
            lut = (lut * 255).astype(np.uint8)

        rgba = lut.take(xa, axis=0, mode='clip')

        if alpha is not None:
            alpha = np.clip(alpha, 0, 1)
            if bytes:
                alpha *= 255  # Will be cast to uint8 upon assignment.
            if alpha.shape not in [(), xa.shape]:
                raise ValueError(
                    f"alpha is array-like but its shape {alpha.shape} does "
                    f"not match that of X {xa.shape}")
            rgba[..., -1] = alpha
            # If the "bad" color is all zeros, then ignore alpha input.
            if (lut[-1] == 0).all():
                rgba[mask_bad] = (0, 0, 0, 0)

        return rgba, mask_bad

    def __copy__(self):
        cls = self.__class__
        cmapobject = cls.__new__(cls)
        cmapobject.__dict__.update(self.__dict__)
        if self._isinit:
            cmapobject._lut = np.copy(self._lut)
        return cmapobject

    def __eq__(self, other):

View on GitHub (pinned to b379c1b69e)

Solutions

  1. Reshape alpha to match the data: cmap(x, alpha=alpha.reshape(x.shape)) or np.broadcast_to(alpha, x.shape).
  2. Pass a scalar alpha when uniform transparency is wanted.
  3. Assert the shape before the call: alpha.shape in ((), x.shape).

Example fix

// before
rgba = cmap(xa, alpha=alpha_2d)  # alpha_2d.shape == (n, 1), xa.shape == (n,)
// after
rgba = cmap(xa, alpha=alpha_2d.reshape(-1))
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def conform_alpha(alpha, xa):
    if alpha is None or np.ndim(alpha) == 0:
        return alpha
    alpha = np.asarray(alpha, dtype=float)
    if alpha.shape == ():
        return float(alpha)
    if alpha.shape != xa.shape and alpha.size == xa.size:
        alpha = alpha.reshape(xa.shape)
    return alpha

Try / catch

try:
    rgba = cmap(xa, alpha=alpha)
except ValueError as e:
    if 'does not match that of X' in str(e):
        rgba = cmap(xa, alpha=np.broadcast_to(alpha, xa.shape))
    else:
        raise

Prevention

When it happens

Trigger: cmap(xa, alpha=np.ones((n, 1))) when xa has shape (n,); an (h, w) per-pixel alpha applied to 1D scatter data; an alpha list converted to a shape that differs from X.

Common situations: Reusing per-pixel opacity masks computed for a 2D image with 1D data; arrays reshaped or raveled between alpha computation and the colormap call; assuming length equality is enough.

Related errors


AI-assisted analysis of matplotlib/matplotlib@b379c1b69e (2026-08-21). Data as JSON: /api/errors/dd56562382ce1670. Report an issue: GitHub.