matplotlib/matplotlib · error · ValueError
Axis limits cannot be NaN or Inf
Error message
Axis limits cannot be NaN or Inf
What it means
When view limits are set, matplotlib converts each limit to a number and rejects non-finite Real values (NaN, +Inf, -Inf), because such limits cannot define a usable view interval. Conversion (e.g. datetime to float) happens first, so only numeric results that are NaN or Inf after conversion raise this ValueError.
Source
Thrown at lib/matplotlib/axes/_base.py:3844
return tuple(self.viewLim.intervalx)
def _validate_converted_limits(self, limit, convert):
"""
Raise ValueError if converted limits are non-finite.
Note that this function also accepts None as a limit argument.
Returns
-------
The limit value after call to convert(), or None if limit is None.
"""
if limit is not None:
converted_limit = convert(limit)
if isinstance(converted_limit, np.ndarray):
converted_limit = converted_limit.squeeze()
if (isinstance(converted_limit, Real)
and not np.isfinite(converted_limit)):
raise ValueError("Axis limits cannot be NaN or Inf")
return converted_limit
def set_xlim(self, left=None, right=None, *, emit=True, auto=False,
xmin=None, xmax=None):
"""
Set the x-axis view limits.
Parameters
----------
left : float, optional
The left xlim in data coordinates. Passing *None* leaves the
limit unchanged.
The left and right xlims may also be passed as the tuple
(*left*, *right*) as the first positional argument (or as
the *left* keyword argument).
.. ACCEPTS: (left: float, right: float)View on GitHub (pinned to b379c1b69e)
Solutions
- Use NaN-aware aggregates: ax.set_xlim(np.nanmin(d), np.nanmax(d)).
- Filter invalid values before plotting: d = d[np.isfinite(d)].
- Validate computed limits: if not np.isfinite(lo) or not np.isfinite(hi), fall back to ax.relim(); ax.autoscale_view() or sensible defaults.
Example fix
# before ax.set_xlim(d.min(), d.max()) # d contains NaN # after ax.set_xlim(np.nanmin(d), np.nanmax(d))
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
lo, hi = compute_limits(data)
if not (np.isfinite(lo) and np.isfinite(hi)):
lo, hi = np.nanmin(data), np.nanmax(data) # or sensible defaults
ax.set_xlim(lo, hi) Try / catch
try:
ax.set_xlim(lo, hi)
except ValueError as e:
if 'NaN or Inf' in str(e):
finite = values[np.isfinite(values)]
ax.set_xlim(finite.min(), finite.max())
else:
raise Prevention
- Use np.nanmin/np.nanmax instead of min/max on possibly-NaN data.
- Filter arrays once: d = d[np.isfinite(d)] before plotting and computing limits.
- Guard divisions used in limit math to avoid producing inf.
When it happens
Trigger: ax.set_xlim(float('nan'), 1) or ax.set_ylim(np.inf, 5); most commonly limits computed from data: d.min()/d.max() on arrays containing NaN; 0/0 or x/0 producing inf/nan in limit arithmetic; limits taken from empty aggregates (np.min([]) -> nan with warning).
Common situations: Real-world datasets with missing values fed straight into limit computation; empty slices after filtering returning nan; unit conversions or scalings introducing inf; interactive apps computing limits from unvalidated user ranges.
Related errors
- Can only output finite numbers in PDF
- Wedge sizes must be finite numbers
- ecdf() does not support NaNs
- aspect must be finite and positive
- z array must not contain non-finite values within the triang
AI-assisted analysis of matplotlib/matplotlib@b379c1b69e (2026-08-21).
Data as JSON: /api/errors/f658884c941cab8f.
Report an issue: GitHub.