matplotlib/matplotlib · error · RuntimeError
You must first set the image array
Error message
You must first set the image array
What it means
_ImageBase.get_shape() and get_size() read self._A, the array installed by set_data/set_array. If the array was never set — typical for an AxesImage constructed directly rather than through imshow — _A is None and the method raises RuntimeError.
Source
Thrown at lib/matplotlib/image.py:319
shape = self.get_shape()
return f"{type(self).__name__}(shape={shape!r})"
except RuntimeError:
return type(self).__name__
def __getstate__(self):
# Save some space on the pickle by not saving the cache.
return {**super().__getstate__(), "_imcache": None}
def get_size(self):
"""Return the size of the image as tuple (numrows, numcols)."""
return self.get_shape()[:2]
def get_shape(self):
"""
Return the shape of the image as tuple (numrows, numcols, channels).
"""
if self._A is None:
raise RuntimeError('You must first set the image array')
return self._A.shape
def set_alpha(self, alpha):
"""
Set the alpha value used for blending - not supported on all backends.
Parameters
----------
alpha : float or 2D array-like or None
"""
martist.Artist._set_alpha_for_array(self, alpha)
if np.ndim(alpha) not in (0, 2):
raise TypeError('alpha must be a float, two-dimensional '
'array, or None')
self._imcache = None
def _get_scalar_alpha(self):View on GitHub (pinned to b379c1b69e)
Solutions
- Call set_array(A) (or set_data(A)) before get_size()/get_shape()
- Prefer creating the artist through ax.imshow(A), which sets data at construction
- Gate shape queries on im.get_array() is not None
Example fix
im = AxesImage(ax) # before h, w = im.get_size() # RuntimeError # after im.set_array(arr) h, w = im.get_size()
Defensive patterns
Strategy: validation
Validate before calling
im = AxesImage(ax)
if im.get_array() is None:
im.set_array(arr)
h, w = im.get_size() Prevention
- Set data immediately after constructing image artists by hand
- Gate shape queries on get_array() is not None
When it happens
Trigger: im = AxesImage(ax) followed by im.get_size() or im.get_shape() before any im.set_array(A) / set_data(A) call.
Common situations: Wrappers or subclasses that build the artist first and attach streamed data later; querying the shape to configure an Axes before the data pipeline has produced the array.
Related errors
- You must first set the image array or the image attribute
- Adjustable 'box' is not allowed in a twinned Axes; use 'data
- set_aspect(..., adjustable='datalim') or axis('equal') are n
- matplotlib does not support generators as input
- The command {_pformat_subprocess(command)} failed and ge
AI-assisted analysis of matplotlib/matplotlib@b379c1b69e (2026-08-21).
Data as JSON: /api/errors/5632c47567f56848.
Report an issue: GitHub.