I am fairly new to programing and have a question regarding matplotlib. I wrote a python script that reads in data from the outfile of another program then prints out the data from one column.
f = open( '/home/student/AstroSimulation/out.0001.z0.753.AHF_halos','r')
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
print(mass)
What I now need to do is have matplotlib take the values printed in 'mass' and plot number versus mean mass. I have read the documents on the matplotlib website, but they are don't really address how to get data from a script(or I just did not see it). If anyone can point me to some documentation that explains how I do this it would be really appreciated. Thank you
You will call matplotlib from within your script, so matplotlib will not "get data from a script" as such. You send it into matplotlib.
You will need to save the masses outside the loop however, but then, it's just a call to the plot()
and show()
functions in it's most basic form:
import matplotlib.pyplot as plt
masses = []
f = open( '/home/student/AstroSimulation/out.0001.z0.753.AHF_halos','r')
f.readline() # Remove header line
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
masses.append(mass)
print(mass)
# If neccessary, process masses in some way
plt.plot(masses)
plt.show()
I was with you right up to "plot the sum over the average". Perhaps you could link to an image that's like the plot you want to make.
In your current script where you print 'mass', you want to append to a list as floating point value:
from matplotlib import pyplot
DATAFILE = '/home/student/AstroSimulation/out.0001.z0.753.AHF_halos'
MASS_COL = 8
masses = []
with open(DATAFILE) as f:
f_it = iter(f) #get an iterator for f
next(f_it) #skip the first line
for n, line in enumerate(f_it): #now the for loop uses f_it
row = line.strip().split()
if len(row) > MASS_COL:
mass = row[MASS_COL]
try:
mass = float(mass)
masses.append(mass)
print "%0.3f" % mass
except ValueError:
print "Error (line %d): %s" % (n, mass)
#crunch mass data
plot_data = ...
#make a plot
pyplot.plot(plot_data)
pyplot.show()
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.