How to plot data from multiple files in a loop using matplotlib in python?
<p>I have a more than 1000 files which are .CSV (data_1.csv......data1000.csv), each containing X and Y values !</p>

<pre><code>x1  y1   x2  y2
5.0 60  5.5 500
6.0 70  6.5 600
7.0 80  7.5 700
8.0 90  8.5 800
9.0 100 9.5 900
</code></pre>

<hr>

<p>I have made a subplot program in python which can give two plots (plot1-X1vsY1, Plot2-X2vsY2) at a time using one file.
I need help in looping all the files, (open a file, read it, plot it, pick another file, open it, read it, plot it, then next ..... till all the files in a folder gets plotted)</p>

<h2>I have made a small code:</h2>

<pre><code>import pandas as pd
import matplotlib.pyplot as plt

df1=pd.read_csv("data_csv",header=1,sep=',')
fig = plt.figure()
plt.subplot(2, 1, 1)
plt.plot(df1.iloc[:,[1]],df1.iloc[:,[2]])

plt.subplot(2, 1, 2)
plt.plot(df1.iloc[:,[3]],df1.iloc[:,[4]])

plt.show()
</code></pre>

<p>Any loop structure to do this task more efficiently ??</p>

<p>You can generate a list of filenames using <code>glob</code> and then plot them in a for loop.</p>

<pre><code>import glob
import matplotlib.pyplot as plt

files = glob.glob(# file pattern something like '*.csv')

for file in files:
    df1=pd.read_csv(file,header=1,sep=',')
    fig = plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(df1.iloc[:,[1]],df1.iloc[:,[2]])

    plt.subplot(2, 1, 2)
    plt.plot(df1.iloc[:,[3]],df1.iloc[:,[4]])
    plt.show() # this wil stop the loop until you close the plot
</code></pre>

python loops csv matplotlib plot