Axes from plt.subplots() is a "numpy.ndarray" object and has no attribute "plot"

The axes are in 2-d, not 1-d so you can't iterate through using one loop. You need one more loop:

 fig,axes=plt.subplots(nrows=2,ncols=2)
    plt.tight_layout()
    for ho in axes:
        for i in ho:
            i.plot(a,a**2)

This gives no problem but if I try:

for i in axes:
      i.plot(a,a**2)

the error occurs.


If you debug your program by simply printing ax, you'll quickly find out that ax is a two-dimensional array: one dimension for the rows, one for the columns.

Thus, you need two indices to index ax to retrieve the actual AxesSubplot instance, like:

ax[1,1].plot(...)

If you want to iterate through the subplots in the way you do it now, by flattening ax first:

ax = ax.flatten()

and now ax is a one dimensional array. I don't know if rows or columns are stepped through first, but if it's the wrong around, use the transpose:

ax = ax.T.flatten()

Of course, by now it makes more sense to simply create each subplot on the fly, because that already has an index, and the other two numbers are fixed:

for x < plots_tot:
     ax = plt.subplot(nrows, ncols, x+1)

Note: you have x <= plots_tot, but with x starting at 0, you'll get an IndexError next with your current code (after flattening your array). Matplotlib is (unfortunately) 1-indexed for subplots. I prefer using a 0-indexed variable (Python style), and just add +1 for the subplot index (like above).


The problem here is with how matplotlib handles subplots. Just do the following:

fig, axes = plt.subplots(nrows=1, ncols=2)
for axis in axes:
    print(type(axis))

you will get a matplotlib object which is actually a 1D array which can be traversed using single index i.e. axis[0], axis[1]...and so on. But if you do

fig, axes = plt.subplots(nrows=2, ncols=2)
for axis in axes:
    print(type(axis))

you will get a numpy ndarray object which is actually a 2D array which can be traversed only using 2 indices i.e. axis[0, 0], axis[1, 0]...and so on. So be mindful how you incorporate your for loop to traverse through axes object.


In case if you use N by 1 graphs, for example if you do like fig, ax = plt.subplots(3, 1) then please do likeax[plot_count].plot(...)