{"record":{"id":"d0bc26ff576f6b59","repo":"matplotlib/matplotlib","slug":"n-axes-must-be-positive-and-not-larger-than-nrows","errorCode":null,"errorMessage":"n_axes must be positive and not larger than nrows*ncols","messagePattern":"n_axes must be positive and not larger than nrows\\*ncols","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/mpl_toolkits/axes_grid1/axes_grid.py","lineNumber":124,"sourceCode":"            - \"L\": All axes on the left column get vertical tick labels;\n              all axes on the bottom row get horizontal tick labels.\n            - \"1\": Only the bottom left axes is labelled.\n            - \"all\": All axes are labelled.\n            - \"keep\": Do not do anything.\n\n        axes_class : subclass of `matplotlib.axes.Axes`, default: `.mpl_axes.Axes`\n            The type of Axes to create.\n        aspect : bool, default: False\n            Whether the axes aspect ratio follows the aspect ratio of the data\n            limits.\n        \"\"\"\n        self._nrows, self._ncols = nrows_ncols\n\n        if n_axes is None:\n            n_axes = self._nrows * self._ncols\n        else:\n            if not 0 < n_axes <= self._nrows * self._ncols:\n                raise ValueError(\n                    \"n_axes must be positive and not larger than nrows*ncols\")\n\n        self._horiz_pad_size, self._vert_pad_size = map(\n            Size.Fixed, np.broadcast_to(axes_pad, 2))\n\n        _api.check_in_list([\"column\", \"row\"], direction=direction)\n        self._direction = direction\n\n        if axes_class is None:\n            axes_class = self._defaultAxesClass\n        elif isinstance(axes_class, (list, tuple)):\n            cls, kwargs = axes_class\n            axes_class = functools.partial(cls, **kwargs)\n\n        kw = dict(horizontal=[], vertical=[], aspect=aspect)\n        if isinstance(rect, (Number, SubplotSpec)):\n            self._divider = SubplotDivider(fig, rect, **kw)\n        elif len(rect) == 3:","sourceCodeStart":106,"sourceCodeEnd":142,"githubUrl":"https://github.com/matplotlib/matplotlib/blob/b379c1b69e012b142c0f496a52bcb30513802d72/lib/mpl_toolkits/axes_grid1/axes_grid.py#L106-L142","documentation":"When constructing `ImageGrid`/`Grid` (mpl_toolkits.axes_grid1.axes_grid) with an explicit `n_axes`, the value must satisfy 0 < n_axes <= nrows*ncols from the `nrows_ncols` pair. Zero, negative values, or values larger than the grid capacity raise ValueError. Omitting n_axes entirely defaults it to exactly nrows*ncols and never triggers this error.","triggerScenarios":"ImageGrid(fig, rect, nrows_ncols=(2, 2), n_axes=0); n_axes=5 with nrows_ncols=(2, 2); n_axes computed as len(images) where images outgrew the configured grid; n_axes=-1 intended to mean 'all'.","commonSituations":"Parameterizing grid size and image count independently in a plotting function so they drift apart; passing n_axes=len(data) while nrows_ncols comes from a config file; assuming n_axes=0 or None disables the check (None does skip it; 0 does not).","solutions":["Omit n_axes so it defaults to nrows*ncols","Derive the grid from the data: nrows_ncols sized so rows*cols >= n_axes","If you pass n_axes explicitly, assert 0 < n_axes <= nrows*ncols first","For 'all axes' semantics pass n_axes=nrows*ncols or None"],"exampleFix":"# before\ngrid = ImageGrid(fig, 111, nrows_ncols=(2, 2), n_axes=len(images))  # len=5 fails\n\n# after\nn = len(images)\ngrid = ImageGrid(fig, 111, nrows_ncols=(2, (n + 1) // 2), n_axes=n)","handlingStrategy":"validation","validationCode":"rows, cols = nrows_ncols\nif n_axes is not None and not 0 < n_axes <= rows * cols:\n    nrows_ncols = (max(1, (n_axes + cols - 1) // cols), cols)\ngrid = ImageGrid(fig, 111, nrows_ncols=nrows_ncols, n_axes=n_axes)","typeGuard":"def grid_holds(nrows_ncols, n_axes):\n    rows, cols = nrows_ncols\n    return n_axes is None or 0 < n_axes <= rows * cols","tryCatchPattern":"try:\n    grid = ImageGrid(fig, 111, nrows_ncols=nrows_ncols, n_axes=n_axes)\nexcept ValueError:\n    grid = ImageGrid(fig, 111, nrows_ncols=nrows_ncols)  # default: all cells","preventionTips":["Derive nrows_ncols from the data length instead of hardcoding both","Prefer omitting n_axes when you want the full grid","Assert 0 < n_axes <= rows*cols when both come from separate sources"],"tags":["matplotlib","axes-grid","imagegrid","argument-validation"],"backgroundTag":"invalid-argument-value","analyzedSha":"b379c1b69e012b142c0f496a52bcb30513802d72","analyzedAt":"2026-08-21T23:31:55.468Z","schemaVersion":2},"datasetVersion":"2026-08-22T04:17:13.399Z"}