How to plot data from multiple files in a loop using matplotlib in python? -


i have more 1000 files .csv (data_1.csv......data1000.csv), each containing x , y values !

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 

i have made subplot program in python can give 2 plots (plot1-x1vsy1, plot2-x2vsy2) @ time using 1 file. need in looping files, (open file, read it, plot it, pick file, open it, read it, plot it, next ..... till files in folder gets plotted)

i have made small code:

import pandas pd import matplotlib.pyplot 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() 

any loop structure task more efficiently ??

you can generate list of filenames using glob , plot them in loop.

import glob import matplotlib.pyplot plt  files = glob.glob(# file pattern '*.csv')  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() # wil stop loop until close plot 

Comments