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

1 投票
2 回答
5506 浏览
提问于 2025-04-18 06:05

我写了一个函数,用来绘制一维数组 theta 的直方图。但是我不太喜欢这个函数的一点,就是数据直接写在代码里。你知道怎么把数据放在一个文件里,然后让这个函数从文件中读取数据吗?因为数据通常会大得多。

附注:代码如下

#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 个回答

2

如果你有一个文本文件,第一行是用逗号分隔的theta值,第二行是箱子的数量:

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

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

撰写回答