2011-08-24 75 views
1

我對編程頗爲陌生,對matplotlib有疑問。我編寫了一個python腳本,它從另一個程序的outfile中讀入數據,然後從一列中打印出數據。如何將數據從python腳本發送到Matplotlib?

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

@eryksun是的數據是所有在列8列8中的每一行有一個值,我必須做的是取第8列中所有值的平均值(總計第8列的每一行中的值,並將其除以第8列中的總行數),並將其與行數。我很抱歉,如果我沒有清楚解釋我必須做什麼,並再次感謝您的幫助。 – Surfcast23

回答

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

謝謝,我會試試 – Surfcast23

+0

我正在嘗試使用腳本以及eryksun的腳本來做到這一點。 (我認爲能夠以不止一種方式做到這一點很有意義)我試圖用下面的方式去掉列中的第一行,這是一個字符串,但它不適用於上面的腳本。你能解釋爲什麼嗎?謝謝 – Surfcast23

+0

eryksun使用不同的方法,並使用顯式迭代器。如果要刪除此方法的第一行,只需在'for'循環之前調用'f.readline()'。另外,我注意到我的縮進中有一個錯誤,我現在要修復它... – carlpett

1

我是你,一直到「繪製平均值的總和「。也許你可以鏈接到一個像你想要製作的情節的圖像。

在當前的腳本,您打印「大衆」,要追加到列表的浮點值:

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

感謝您的建議,我會嘗試一下。 – Surfcast23

+0

我有另一個問題。你如何刪除列的第一行?我的批量列中的第一行是我需要刪除的字符串,因爲它會導致錯誤。 – Surfcast23

+0

再次感謝您的幫助 – Surfcast23