2014-05-10 57 views
1

我寫了一個函數來繪製一維數組theta的直方圖。但是我不喜歡這個函數的一點是數據在代碼中。你能知道如何將數據保存在文件中,並使其功能從文件中讀取?由於數據通常要大得多。使用python繪製直方圖時從文件讀取數據的方法?

PS:該代碼是

#hist.py 
import matplotlib.mlab as mlab 
import matplotlib.pyplot as plt 

theta=[77.438110,82.811340,59.701530,124.94859,82.991272,84.300468,24.639610,112.28130] 
num_bins = 72 
# the histogram of the data 
n, bins, patches = plt.hist(theta, num_bins, range=[0,180], normed = True, histtype='bar',facecolor='green') 
plt.xlabel(r'$\theta$($\degree$)') 
plt.ylabel(r'$P(\theta)$') 
plt.show() 
+0

從直方圖中讀取數據是什麼意思?你已經在變量'n'和'bin'中使用了... –

+0

@jiadong,數據來自何處? –

+0

@SaulloCastro如果數組theta包含更大數量的條目,例如10000,那麼用這種方式定義它'theta = [77.438110,...,112.28130]'是不好的。我將theta的元素保存在另一個文件中,然後我想找到如何從文件中讀取數據。 – jiadong

回答

2

假設每個數據項是在單獨的行中的theta.dat文件theta.dat是當前的工作目錄。

theta=[] 
with open("theta.dat") as f: 
    for line in f: 
     theta.append(float(line)) 
print theta 
[77.43811, 82.81134, 59.70153, 124.94859, 82.991272, 84.300468, 24.63961, 112.2813] 

只是運行你的代碼,因爲你有,我已經在打印聲明只是爲了向你展示數據結構的外觀。

num_bins = 72 
# the histogram of the data 
n, bins, patches = plt.hist(theta, num_bins, range=[0,180], normed = True,  histtype='bar',facecolor='green') 
plt.xlabel(r'$\theta$($\degree$)') 
plt.ylabel(r'$P(\theta)$') 
plt.show() 
+0

謝謝。它運作良好。我明白你的意思了。另外一件事情應該改變是用它的路徑來代替「theta.dat」。所以我希望這對其他人來說已經夠清楚了。 – jiadong

+0

沒問題。別客氣。 –

2

如果你有在第一線與分離逗號THETA值的txt文件,並在第二行窗口的數量:

77.438110,82.811340,59.701530,124.94859,82.991272,84.300468,24.639610,112.28130 
72 

可以補充一點:

import numpy as np 
from StringIO import StringIO 

def read(file_name): 
    f = open(file_name,'r') 
    data = f.readlines() 
    f.close() 
    theta = np.genfromtxt(StringIO(data[0]), delimiter=",") 
    num_bins = data[1] 
    return theta, num_bins 

實施例:

theta, num_bins = read("data_file.txt") 
n, bins, patches = plt.hist(theta, num_bins, range=[0,180], normed = True,  histtype='bar',facecolor='green') 
plt.xlabel(r'$\theta$($\degree$)') 
plt.ylabel(r'$P(\theta)$') 
plt.show() 

http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html

+0

非常有幫助。 +1 – jiadong