0

I would like to write a program that creates 100 masked plots from a spread of 100 text files. i.e. for fnum in range(1,100,1):

The text files are numbered xydata1.txt, xydata2.txt ... until xydata100.txt.

How is this best done in Python?

Below is my plotting program, where (file number fnum) = 1,2,3...100.

    fn = 'xydata'+fnum+'.txt'
    y = loadtxt(fn,unpack=True,usecols=[0])
    x = loadtxt(fn,unpack=True,usecols=[1])

    n = ma.masked_where(gradient(y) < 0, y)
    p = ma.masked_where(gradient(y) > 0, y)

    pylab.plot(x,n,'r',x,p,'g')

    pylab.savefig('data'+fnum+'.png')
    pylab.show()

1 Answer 1

1

Assuming Python 2.7

from glob import glob
from pylab import *


for fname in glob("xydata*.txt"):
    x, y = loadtxt(fname, unpack=True, usecols=[1, 0])
    mask_inf = gradient(y) < 0
    mask_sup = gradient(y) >= 0

    plot(x[mask_inf], y[mask_inf], 'r')
    plot(x[mask_sup], y[mask_sup], 'g')

    legend(("grad(y) < 0", "grad(y) >= 0"))
    title(fname)

    savefig(fname.replace("xydata", "data").replace(".txt", ".svg"))
    clf()

You can also use masked arrays. But the only advantage of them is to avoid allocating new memory. If your plots are small enough, you don't need them.

By the way there is no "best answer".

Sign up to request clarification or add additional context in comments.

4 Comments

Say if I had a file full of temperatures, called T.txt, how would I then go onto extracting a value of T from that file that is of the row order of * for use in each plot's title?
I don't quite understand what you are up to. Could you elaborate a bit? You have a file full of temperature. You want to extract them, and then? What do you want to plot? What do you want to do with the titles?
Oh, sorry I explained that badly. I would like to make all of the plots for the xydata*.txt files (as achieved by your answer code). I would also like to extract values of temperature, from a file T.txt, which takes values from each row of the T.txt file for every * iteration. This value of T would be printed each graph's title.
I guess I understood correctly. I was about to give you an answer, but you have to work a bit on it too... Here are some hint on how I would do it: Just load the column of interest from T.txt in separate variables (temperature for instance). Replace the use of glob by a for iteration over xrange(100), exactly as you did first. Create each filename from it (just as you did) and when comes the time to specify the title, just use temperature[i] with i, the current iteration step. In short: you just have to add 2 lines and replace one. Easy...

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.