matplotlib/matplotlib · error · ValueError

For X ({width}) and Y ({height}) with {self._shading} shadin

Error message

For X ({width}) and Y ({height}) with {self._shading} shading, A should have shape {' or '.join(map(str, ok_shapes))}, not {A.shape}

What it means

QuadMesh.set_array (backing pcolormesh) validates that the color array A matches the mesh geometry. With shading='flat' and (height, width) vertex coordinates, A must be (height-1, width-1), optionally with a trailing 3 or 4 for RGB(A), or flat size (height-1)*(width-1); with 'gouraud'/'nearest' shading A must match the full (height, width). The message lists the exact shapes expected for your mesh.

Source

Thrown at lib/matplotlib/collections.py:2387

            If the values are provided as a 2D grid, the shape must match the
            coordinates grid. If the values are 1D, they are reshaped to 2D.
            M, N follow from the coordinates grid, where the coordinates grid
            shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat'
            shading.
        """
        height, width = self._coordinates.shape[0:-1]
        if self._shading == 'flat':
            h, w = height - 1, width - 1
        else:
            h, w = height, width
        ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)]
        if A is not None:
            if hasattr(self, 'norm'):
                A = mcolorizer._ensure_multivariate_data(A, self.norm.n_components)
            shape = np.shape(A)
            if shape not in ok_shapes:
                raise ValueError(
                    f"For X ({width}) and Y ({height}) with {self._shading} "
                    f"shading, A should have shape "
                    f"{' or '.join(map(str, ok_shapes))}, not {A.shape}")
        return super().set_array(A)

    def get_coordinates(self):
        """
        Return the vertices of the mesh as an (M+1, N+1, 2) array.

        M, N are the number of quadrilaterals in the rows / columns of the
        mesh, corresponding to (M+1, N+1) vertices.
        The last dimension specifies the components (x, y).
        """
        return self._coordinates

    def get_edgecolor(self):
        # docstring inherited
        # Note that we want to return an array of shape (N*M, 4)

View on GitHub (pinned to b379c1b69e)

Solutions

  1. Match A to the mesh: for flat shading with (M+1, N+1) coordinates pass A of shape (M, N); for 'nearest'/'gouraud' pass A of the same shape as the coordinates
  2. Reshape or slice the color array to one of the accepted shapes listed in the message (2-D, 3-D with 3/4 channels, or flattened)
  3. Use shading='auto' to let matplotlib infer the convention from the input shapes
  4. If mutating later, call set_array with an array of the same shape as the original

Example fix

// before
X, Y = np.meshgrid(x, y)          # (11, 11)
mesh = ax.pcolormesh(X, Y, C11)   # C11 is (11, 11), shading='flat' -> error
// after
mesh = ax.pcolormesh(X, Y, C10)   # flat shading: A is (10, 10) cells
// or
mesh = ax.pcolormesh(X, Y, C11, shading='nearest')
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def expected_a_shapes(coords, shading):
    h, w = np.asarray(coords).shape[:2]
    if shading == 'flat':
        h, w = h - 1, w - 1
    return {(h, w, 3), (h, w, 4), (h, w), (h * w,)}

# before set_array / pcolormesh
if np.shape(A) not in expected_a_shapes(coords, shading):
    raise ValueError(f'A must be one of {expected_a_shapes(coords, shading)}, got {np.shape(A)}')

Type guard

def quadmesh_array_ok(coords, A, shading):
    return np.shape(A) in expected_a_shapes(coords, shading)

Try / catch

try:
    mesh.set_array(A)
except ValueError as e:
    if 'should have shape' in str(e):
        A = A.reshape(expected_shape)  # or log and skip the update
        mesh.set_array(A)
    else:
        raise

Prevention

When it happens

Trigger: ax.pcolormesh(X, Y, C) where C's shape does not match X/Y under the active shading; mesh.set_array(arr) with a wrong-shape array; the classic off-by-one of passing (M+1, N+1) corner coordinates with a (M+1, N+1) color array under flat shading; passing an RGBA array whose first two dims do not match the mesh.

Common situations: Mixing imshow-style arrays (same shape as coordinates) with pcolormesh's cell-based convention; upgrading matplotlib versions where the default shading changed (older code relying on implicit 'flat' with same-shape inputs now needs shading='nearest'); swapping in a downsampled color array while keeping full-resolution coordinates.

Related errors


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