Seperate title for each subplot in a for loop in Python

Viewed 1278

I am trying to use subplots within a for loop and I can plot all my graphs, but I can't give them individual x and y labels and titles. It is only the last one that it is applied to.

import numpy as np
import astropy
import matplotlib.pyplot as plt
import pandas as pd

#Import 18 filesnames with similar names
from glob import glob
filenames = glob('./*V.asc')
df = [np.genfromtxt(f) for f in filenames]

A = np.stack(df, axis=0)

#Begin subplot
nrows = 3
ncols = 6
fig, ax = plt.subplots(nrows = nrows, ncols = ncols, figsize=(30,15))

#Loop over each filename i, row j and column k
i = 0
for j in range(0, nrows):
    for k in range(0, ncols):
        ax[j,k].plot(A[i,:,0], A[i,:,1])
        plt.title(filenames[i], fontsize = '25')
        i += 1
        plt.subplots_adjust(wspace=.5, hspace=.5)

fig.show()

I can plot it in seperate plots, so 18 in total and it works fine

for i in range(0, len(A)):

    plt.figure(i)
    plt.title(filenames[i], fontsize = '30')
    plt.plot(A[i,:,0], A[i,:,1])
    plt.xlabel('Wavelength [Å]', fontsize = 20)
    plt.ylabel('Flux Density [erg/s/cm^2/Å]', fontsize = 20)
    plt.xticks(fontsize = 20)
    plt.yticks(fontsize = 20)
    

I update the title each iteration i, same as the subplot, so I don't understand why it doesn't work. Any input is appreciated!

1 Answers

plt.title() acts on the current axes, which is generally the last created, and not the Axes that you are thinking of.

In general, if you have several axes, you will be better off using the object-oriented interface of matplotlib rather that the pyplot interface. See usage guide

replace:

plt.title(filenames[i], fontsize = '25')

by

ax[j,k].set_title(filenames[i], fontsize = '25')
Related