使用python绘制直方图时从文件中读取数据的方法?

时间:2014-05-10 08:28:17

标签: python matplotlib plot histogram

我写了一个函数来绘制一维数组θ的直方图。但是我在这个函数中不喜欢的一件事是数据在代码中。你能知道如何将数据保存在文件中并使函数从文件中读取吗?由于数据通常要大得多。

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

2 个答案:

答案 0 :(得分:2)

假设每个数据条目位于theta.dat文件的不同行,而the.d.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]

只需运行您的代码,我已经在print语句中展示了数据结构的外观。

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

答案 1 :(得分:2)

如果你有一个txt文件,第一行包含分隔的逗号theta值,第二行包含bin的数量:

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