« Return to Thread: How do you Plot data generated by a python script?

Re: How do you Plot data generated by a python script?

by surfcast23 :: Rate this Message:

| View in Thread

Hi Martin,

     Thank for the relpy.  What I have is a script that reads the data from a large file then prints out the values listed in a particular column. What I now need to do is have the information in that column plotted as the number of rows vs. the mean value of all of the rows. What I have so far is

import matplotlib.pyplot as plt

masses = []

f = open( 'myfile.txt','r')
f.readline()
for line in f:
 if line != ' ':      
    line = line.strip()          # Strips end of line character
    columns = line.split()    # Splits into coloumn
    mass = columns[8]      # Column which contains mass values
    mass = float(mass)
    masses.append(mass)
    print(mass)

plt.plot()
plt.show


I am thinking I can do something like

'y runs fron 0 to n where n == len(masses) '
x = 'mass_avg = sum(masses)/len(masses)'

Problem is I don' tknow how to have matplotlib do it with out giving me an error about dimentions. I would also like to do this with out having to write and read from another file. I alos need to to be able to work on files with ddifering numbers of rows.

Thanks




mdekauwe wrote:
I wasn't quite able to follow exactly what you wanted to do but maybe this will help. I am going to generate some "data" that I think sounds a bit like yours, write it to a file, clearly you already have this. Then I am going to read it back in and plot it, e.g.

import matplotlib.pyplot as plt
import numpy as np

# Generate some data a little like yours, I think?
# print it to a file, i.e. I am making your myfile.txt
numrows = 100
numcols = 8
mass = np.random.normal(0, 1, (numrows  * numcols)).reshape(numrows, numcols)
f = open("myfile.txt", "w")
for i in xrange(numrows):
    for j in xrange(numcols):
        print >>f,  mass[i,j],
    print >> f
f.close()    

# read the file back in
mass = np.loadtxt("myfile.txt")

# plot the 8th column
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(mass[:,7], 'r-o')
ax.set_xlabel("Time")
ax.set_ylabel("Mass")
plt.show()


I wasn't clear on the mean bit, but that is easy to do with numpy, e.g.

mean_mass = np.mean(mass[:,8])

etc.

Numpy et al is great for stuff like this.

Hope that helps,

Martin

 « Return to Thread: How do you Plot data generated by a python script?