Without knowing what your file contains and how they look, here is the basic idea which you can adapt to your example. Here, I store the names of the files you want to read in a list and then I loop over the subplots one at a time. I use enumerate
to get the axis instance and the index so that I can access/loaf files one at a time. P.S: I used np.loadtxt
just as an example. You can basically replace the commands with whatever way you want to load files.
Instead of axes.ravel()
, you can also use either axes.flatten()
or axes.flat
.
fig, axes = plt.subplots(nrows=3, ncols=1)
files = ['file1.txt', 'file2.txt', 'file3.txt']
for i, ax in enumerate(axes.ravel()): # or axes.flatten() or axes.flat
data1=np.loadtxt(files[i])
data2=np.loadtxt(files[i])
ax.plot(data1, data2)
plt.tight_layout() # To get a better spacing between the subplots
Alternative solution without using ravel
and enumerate
as suggested by Tom de Geus is:
for i in range(3):
axes[i].plot(x, y, label='File %d' %i)
axes[i].legend()
Following is a simple example to showcase the idea (Same can be done using the above alternative solution)
fig, axes = plt.subplots(nrows=3, ncols=1)
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
for i, ax in enumerate(axes.ravel()): # or axes.flatten() or axes.flat
ax.plot(x, y, label='File %d' %i)
ax.legend()
fig.text(0.5, 0.01, 'X-label', ha='center')
fig.text(0.01, 0.5, 'Y-label', va='center', rotation='vertical')
plt.tight_layout() # To get a better spacing between the subplots
