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).