我对编程很新,对matplotlib有疑问。我写了一个python脚本,从另一个程序的outfile中读取数据,然后从一列打印出数据。
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)
我现在需要做的是让matplotlib以“质量”打印的值和图数与平均质量相对应。我已经阅读了matplotlib网站上的文档,但它们并没有真正解决如何从脚本中获取数据(或者我只是没有看到它)。如果有人能指出我的一些文档来解释我是如何做到的,那将非常感激。谢谢
答案 0 :(得分:2)
您将在脚本中调用matplotlib,因此matplotlib不会“从脚本中获取数据”。你把它发送到matplotlib。
然而,你需要将质量保存在循环之外,但是,它只是调用plot()
和show()
函数,它是最基本的形式:
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()
答案 1 :(得分:1)
我和你在一起“直接计算总和”。也许你可以链接到一个像你想要制作的情节的图像。
在当前打印'mass'的脚本中,您希望将列表附加为浮点值:
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()