简体   繁体   中英

read and plot multiple txt files in python

I have some output files ie frequency1 .txt , frequency2 .txt and so on (till 21). In each txt files I am having 10 columns and suppose n rows , now I need to plot column 2 and column 3 for all these txt files .I am able to plot for a single txt file

import numpy as np
from matplotlib import pyplot as plt

data=np.loadtxt('frequecy1.txt')
pl.plot(data[:,1],data[:,2],'bo')
X=data[:,1]
Y=data[:,2]
plt.plot(X,Y,':ro')
plt.ylim((0,55000))
plt.show()

How would I plot all the files?

First, there's no need to both import pylab and pyplot. Second, if all your files are structured the same, this code should work:

import numpy as np
import matplotlib.pyplot as plt

for fname in ('frequency1.txt', 'frequency2.txt' ...):
    data=np.loadtxt(fname)
    X=data[:,1]
    Y=data[:,2]
    plt.plot(X,Y,':ro')
plt.ylim((0,55000))
plt.show() #or
plt.save('figure.png')

Just wanted to add something to @Korem's answer. You can create a list of filenames then pass it using for loop instead of writing file names manually.

import numpy as np
import matplotlib.pyplot as plt

filelist=[]

for i in range(1,5):
    filelist.append("frequency%s.dat" %i)

for fname in filelist:
    data=np.loadtxt(fname)
    X=data[:,0]
    Y=data[:,1]
    plt.plot(X,Y,':ro')

plt.show()

instead of

plt.show()

use

plt.save("chart1.png")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM