read and plot multiple txt files in python

夙愿已清 提交于 2021-01-28 01:44:25

问题


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?


回答1:


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')



回答2:


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()



回答3:


instead of

plt.show()

use

plt.save("chart1.png")


来源:https://stackoverflow.com/questions/24725376/read-and-plot-multiple-txt-files-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!