[英]How can I send data from a python script to Matplotlib?
我是編程新手,對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網站上的文檔,但是它們並沒有真正解決如何從腳本獲取數據的問題(或者我只是沒有看到它)。 如果有人能指出我一些說明我如何執行此操作的文檔,將不勝感激。 謝謝
您將在腳本中調用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()
我正和你在一起,“將總和繪制在平均值上”。 也許您可以鏈接到想要繪制的圖像。
在當前腳本中打印“質量”的位置,您希望將其作為浮點值追加到列表中:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.