Matplotlib AttributeError: 'Axes' object has no attribute (and How to Fix It)

Fix Matplotlib's AttributeError messages: 'Axes' object has no attribute 'xlabel', 'numpy.ndarray' object has no attribute 'plot', 'Figure' object has no attribute 'plot', and the others that come from mixing pyplot and Axes names.

AttributeError: 'Axes' object has no attribute 'xlabel' means you called a pyplot function name on an Axes object. On an Axes, most setters start with set_: use ax.set_xlabel(), ax.set_ylabel(), ax.set_title(), ax.set_xlim(), and ax.set_xticks(). The related error 'numpy.ndarray' object has no attribute 'plot' means plt.subplots() gave you a grid of axes, and you need to pick one with axs[0, 1] or loop over axs.flat. The examples use Matplotlib 3.11.

Quick Example

This version creates a 2×2 grid and calls only Axes methods, so none of the errors on this page can happen:

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(8)
hours = np.arange(24)
stations = ["North", "East", "South", "West"]

fig, axs = plt.subplots(2, 2, figsize=(8, 5.5), sharex=True, sharey=True,
                        layout="constrained")
for ax, station, peak in zip(axs.flat, stations, [13, 14, 15, 16]):
    wind = 14 + 7 * np.cos((hours - peak) / 24 * 2 * np.pi) + rng.normal(0, 1.5, 24)
    ax.plot(hours, wind, color="#2a7f62")
    ax.set_title(f"{station} station")   # not ax.title(...)
    ax.set_xlabel("Hour")                # not ax.xlabel(...)
    ax.set_ylabel("Wind (km/h)")         # not ax.ylabel(...)
    ax.set_xlim(0, 23)                   # not ax.xlim(...)
fig.suptitle("Wind speed over one day")  # the figure title lives on fig
plt.show()

Two by two grid of line charts of hourly wind speed at North, East, South, and West stations, each peaking at 22 to 23 km/h between noon and 4 pm and dropping to 5 to 6 km/h overnight

'Axes' object has no attribute 'xlabel'

fig, ax = plt.subplots() gives you an Axes object. pyplot functions like plt.xlabel() act on the current axes, but the matching Axes methods have a set_ prefix:

fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax.xlabel("Hour")
# AttributeError: 'Axes' object has no attribute 'xlabel'. Did you mean: 'clabel'?

Ignore Python's "Did you mean: 'clabel'?" hint. It suggests the closest spelling, and clabel labels contour lines. The fix is ax.set_xlabel("Hour").

pyplot function Axes method
plt.xlabel(), plt.ylabel() ax.set_xlabel(), ax.set_ylabel()
plt.title() ax.set_title()
plt.xlim(), plt.ylim() ax.set_xlim(), ax.set_ylim()
plt.xticks(ticks, labels) ax.set_xticks(ticks, labels)
plt.xscale("log") ax.set_xscale("log")
plt.suptitle() fig.suptitle()
plt.savefig() fig.savefig()
plt.show() no Axes version; keep plt.show()
plt.plot(), plt.bar(), plt.legend(), plt.grid(), plt.text(), plt.axhline() same name on ax

The same rule gives 'Axes' object has no attribute 'xlim', 'xticks', 'ylabel', 'suptitle', 'savefig', and 'show'. ax.title("...") fails differently, with TypeError: 'Text' object is not callable, because ax.title exists: it's the title's Text object, not a function. You get the same TypeError from ax.title() on the axes that df.plot() returns.

The Figure vs Axes guide explains why the two interfaces exist and has a longer translation table.

'numpy.ndarray' object has no attribute 'plot'

plt.subplots(2, 3) returns a NumPy array of Axes, not a single Axes. Calling a plotting method on the whole array fails:

fig, axs = plt.subplots(2, 3)
axs.plot([1, 2, 3])
# AttributeError: 'numpy.ndarray' object has no attribute 'plot'

Pick one panel by its row and column, or loop over all of them:

fig, axs = plt.subplots(2, 3, figsize=(8, 4.5), layout="constrained")
print(type(axs), axs.shape)  # <class 'numpy.ndarray'> (2, 3)

for (row, col), ax in np.ndenumerate(axs):
    ax.text(0.5, 0.5, f"axs[{row}, {col}]", ha="center", va="center",
            family="monospace", fontsize=14)
    ax.set_xticks([])
    ax.set_yticks([])

axs[0, 1].set_facecolor("#fde9c9")  # one panel by index
axs[0, 1].set_title("axs[0, 1].set_title(...)", family="monospace")
plt.show()

Two rows by three columns of empty panels, each labelled with its index from axs[0, 0] to axs[1, 2], with axs[0, 1] shaded and titled to show how to address one panel

The shape of axs depends on the grid:

Call axs is Index with
plt.subplots() one Axes use it directly
plt.subplots(1, 3) or plt.subplots(3, 1) 1-D array axs[0], axs[1], axs[2]
plt.subplots(2, 3) 2-D array axs[0, 1] (row, column)
plt.subplots(2, 3, squeeze=False) or any grid with squeeze=False always 2-D axs[0, 0], even for one panel

Indexing a 2-D grid with one number, axs[0].plot(...), gives the same 'numpy.ndarray' error because axs[0] is the whole first row. In the other direction, fig, axs = plt.subplots(1, 1) returns a single Axes, so axs[0] raises TypeError: 'Axes' object is not subscriptable. Pass squeeze=False when code has to handle any grid size. For loops, axs.flat visits every panel in row order, whatever the shape. The subplots guide covers grids in more detail.

'Figure' object has no attribute 'plot'

The Figure is the whole canvas. It doesn't draw data or hold axis titles, so fig.plot(), fig.set_title(), and fig.set_xlabel() all fail. Draw on the Axes, and use the figure-level names for figure-wide text:

You wrote Use
fig.plot(...) ax.plot(...)
fig.set_title(...) fig.suptitle(...) for the whole figure, ax.set_title(...) for one panel
fig.set_xlabel(...) fig.supxlabel(...) for a shared label, ax.set_xlabel(...) for one panel
fig.set_figsize((8, 4)) fig.set_size_inches(8, 4), or plt.subplots(figsize=(8, 4))

If the code looks right, check the unpacking order. ax, fig = plt.subplots() swaps the names, so ax is the figure and ax.plot() fails with 'Figure' object has no attribute 'plot'. It's always fig, ax = plt.subplots().

module 'matplotlib' has no attribute 'plot'

This one comes from the import. import matplotlib as plt imports the package, which has no plotting functions. Import the pyplot module instead:

import matplotlib.pyplot as plt

A similar message, module 'matplotlib.pyplot' has no attribute 'set_title', is the reverse of the Axes problem: set_title is an Axes method. Use plt.title() with pyplot, or ax.set_title() with an Axes.

'AxesSubplot' object has no attribute ...

This is the same error from Matplotlib 3.6 and earlier, which named the class AxesSubplot. Matplotlib 3.7 merged the subplot classes into Axes, so the same mistake now says 'Axes' object has no attribute .... The fixes above apply to both.

'list' object has no attribute 'set_color'

ax.plot() returns a list of Line2D objects, one per line drawn, even when it draws only one. Unpack it with a trailing comma to get the line itself:

fig, ax = plt.subplots()
line, = ax.plot([3, 1, 2])   # note the comma
line.set_color("#c0392b")
line.set_linewidth(3)
plt.close(fig)

ax.hist() returns a tuple (counts, bin_edges, patches), so ax.hist(...).set_color(...) fails with 'tuple' object has no attribute 'set_color'. Pass color= to ax.hist() instead, or unpack the tuple and loop over the patches.

'FacetGrid' object has no attribute 'set_title'

Seaborn's figure-level functions (relplot, displot, catplot, lmplot) return a FacetGrid, not an Axes. Use the grid's own methods, or reach the underlying Matplotlib objects:

You want On a FacetGrid g
A title for each facet g.set_titles("{col_name}")
One title over the whole grid g.figure.suptitle("Title")
Axis labels g.set_axis_labels("x label", "y label")
The Axes of a single-panel grid g.ax

Seaborn's axes-level functions (scatterplot, histplot, boxplot) return a normal Axes, so ax.set_title() works and ax.xlabel() fails as above. See Seaborn figure-level vs axes-level functions.

TypeError: 'str' object is not callable from plt.title()

If plt.title("...") or plt.xlabel("...") raises 'str' object is not callable, an earlier cell ran plt.title = "..." and replaced the function with a string. Restart the kernel, or run import importlib; importlib.reload(plt), then call the function instead of assigning to it.

All the errors in one table

Error Cause Fix
'Axes' object has no attribute 'xlabel' (or 'ylabel', 'xlim', 'xticks') pyplot name on an Axes ax.set_xlabel(), ax.set_xlim(), ax.set_xticks()
TypeError: 'Text' object is not callable ax.title("...") ax.set_title("...")
'numpy.ndarray' object has no attribute 'plot' plt.subplots(rows, cols) returned an array axs[0, 1].plot() or for ax in axs.flat:
TypeError: 'Axes' object is not subscriptable axs[0] on a 1×1 grid Use axs directly, or plt.subplots(squeeze=False)
'Figure' object has no attribute 'plot' Plotting on the figure, or ax, fig = plt.subplots() fig, ax = plt.subplots(), then ax.plot()
'Figure' object has no attribute 'set_title' Figure titles have their own name fig.suptitle()
module 'matplotlib' has no attribute 'plot' import matplotlib as plt import matplotlib.pyplot as plt
module 'matplotlib.pyplot' has no attribute 'set_title' Axes name on pyplot plt.title() or ax.set_title()
'AxesSubplot' object has no attribute ... Same as 'Axes', Matplotlib 3.6 or older Same fixes
'list' object has no attribute 'set_color' ax.plot() returns a list line, = ax.plot(...)
'FacetGrid' object has no attribute 'set_title' Seaborn figure-level function g.figure.suptitle(), g.set_titles()
TypeError: 'str' object is not callable plt.title = "..." overwrote the function Restart the kernel

If there's no error but no chart either, see Matplotlib plot not showing.

Similar Topics