Reputation: 155
I have to load 3 numpy files using for loop. After loading data I want to plot 3 subplots because I want to make a comparison between them. If I don't apply for loop and load files one by one then I can easily do that. But is there any way that I load data in for loop and then make 3 subplots.
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
ind1 =[1,2,3]
ind2 = [4,5,6]
for i in range(len(3)):
data1=np.load(..)
data2=np.load(..)
ax1.plot(data1, data2)
Upvotes: 0
Views: 473
Reputation: 39052
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
Upvotes: 2