matplotlib/matplotlib · error · ValueError
axis(= ) out of bounds
Error message
axis(=%s) out of bounds
What it means
The built-in detrend implementations (detrend_mean here, likewise detrend_linear and detrend_none) subtract their statistic along axis and validate it first: if axis is not None and axis + 1 > x.ndim, ValueError. Calling the helper directly with a 1-D array and axis=1 is the classic trigger, since the mlab.detrend wrapper is bypassed.
Solutions
- Call with axis=None (or axis=0) for 1-D data; both behave identically here
- Route through mlab.detrend(x, key='mean', axis=...), which forwards the axis correctly
- Check np.ndim(x) before choosing the axis value
Example fix
import numpy as np # before y = mlab.detrend_mean(x, axis=1) # x is 1-D -> ValueError # after y = mlab.detrend_mean(x, axis=None)
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
if axis is not None and axis >= np.ndim(x):
axis = None
y = mlab.detrend_mean(x, axis=axis) Try / catch
try:
y = mlab.detrend_mean(x, axis=axis)
except ValueError as err:
if 'out of bounds' in str(err):
y = mlab.detrend_mean(x, axis=None)
else:
raise Prevention
- For 1-D data always pass axis=None to the detrend_* helpers
- Gate axis parameters on np.ndim(x) in any generic preprocessing utility
When it happens
Trigger: mlab.detrend_mean(x_1d, axis=1); mlab.detrend_linear(np.array([1.0, 2.0]), axis=1); axis constants from multi-channel pipelines plumbed into these helpers for 1-D segments.
Common situations: Calling detrend_mean/detrend_linear directly for speed; reusing 2-D preprocessing constants in single-channel scripts; per-segment processing inside psd-like code.
Related errors
- axis(= ) out of bounds
- Unknown value for key
- y cannot have ndim > 1
- `bw_method` should be 'scott', 'silverman', a scalar or a…
- Coherence is calculated by averaging over *NFFT* length…
AI-assisted analysis of matplotlib/matplotlib@b379c1b69e (2026-08-21).
Data as JSON: /api/errors/31dd8c3a3bda223d.
Report an issue: GitHub.
Appendix: source
Thrown at lib/matplotlib/mlab.py:153
----------
x : array or sequence
Array or sequence containing the data
Can have any dimensionality
axis : int
The axis along which to take the mean. See `numpy.mean` for a
description of this argument.
See Also
--------
detrend_linear : Another detrend algorithm.
detrend_none : Another detrend algorithm.
detrend : A wrapper around all the detrend algorithms.
"""
x = np.asarray(x)
if axis is not None and axis+1 > x.ndim:
raise ValueError('axis(=%s) out of bounds' % axis)
return x - x.mean(axis, keepdims=True)
def detrend_none(x, axis=None):
"""
Return *x*: no detrending.
Parameters
----------
x : any object
An object containing the data
axis : int
This parameter is ignored.
It is included for compatibility with detrend_mean
See AlsoView on GitHub (pinned to b379c1b69e)