2

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?

3
  • I don't know numpy at all, but you could hack this by writing all the data to a single file with open('path/to/outfile', 'a') as outfile: for infilepath in infilepaths: with open(infilepath) as infile: outfile.write(infile.read()+"\n") then loading that Commented Jul 13, 2014 at 17:40
  • The question is not clear. Do you want to plot them on the same graph? separate graphs? what's the difference you're trying to achieve between blue and red in your example? Commented Jul 13, 2014 at 17:46
  • Actually that happened mistakenly red and blue , I am sorry for that ,I want separate plots for all txt files Commented Jul 13, 2014 at 20:23

3 Answers 3

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

instead of

plt.show()

use

plt.save("chart1.png")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.