Python 分析matplotlib条形图外部文件中的数据
我想从有两列的文本文件中读取数据。这是对先前提出的问题的后续。虽然我的问题与类似,但我无法让我定义的变量与条形图一起工作。目标是从包含两列的文件中读入数据 我第一次尝试使用Python 分析matplotlib条形图外部文件中的数据,python,matplotlib,Python,Matplotlib,我想从有两列的文本文件中读取数据。这是对先前提出的问题的后续。虽然我的问题与类似,但我无法让我定义的变量与条形图一起工作。目标是从包含两列的文件中读入数据 我第一次尝试使用genfromtxt,它在当前代码中被注释掉,但是接收到AttributeError:'numpy.ndarray'对象没有属性“split”。这可能是由于数据是以数组类型格式读取的: >>> import numpy as np >>> data = np.genfromtxt('inpu
genfromtxt
,它在当前代码中被注释掉,但是接收到AttributeError:'numpy.ndarray'对象没有属性“split”
。这可能是由于数据是以数组类型格式读取的:
>>> import numpy as np
>>> data = np.genfromtxt('input-file', delimiter = ' ')
>>> print(data)
[[ 72. 1.]
[ 9. 2.]
[ 10. 36.]
[ 74. 6.]
[ 0. 77.]
[ 5. 6.]
[ 6. 23.]
[ 72. 1.]
[ 9. 2.]
[ 10. 36.]
[ 82. 1.]
[ 74. 6.]
[ 0. 97.]
[ 5. 6.]
[ 6. 23.]
[ 72. 1.]
[ 9. 2.]
[ 10. 36.]
[ 82. 1.]]
接下来,我直接读取数据,但接收到AttributeError:“file”对象没有属性“split”
import numpy as np
import matplotlib.pyplot as plt
data = open('input-file', 'r')
#data = np.genfromtxt('input-file', delimiter = ' ')
counts = []
values = []
for line in data.split("\n"):
x, y = line.split()
values.append(int(x))
counts.append(int(y))
#bar_width = 0.25
#opacity = 0.4
plt.bar(values, counts, color='g')
plt.ylabel('Frequency')
plt.xlabel('Length')
plt.title('Title')
plt.show()
输入文件中的示例内容
72 1
9 2
10 36
74 6
0 77
5 6
6 23
72 1
9 2
10 36
82 1
74 6
0 97
5 6
6 23
72 1
9 2
10 36
82 1
文件对象没有拆分功能。无需拆分(“\n”)
是什么阻止您直接打印从
np.genfromtext
返回的numpy数组的列
data = np.genfromtxt('tmp.dat', delimiter = ' ')
plt.bar(data[:,0], data[:,1], color='g')
plt.ylabel('Frequency')
plt.xlabel('Length')
plt.title('Title')
plt.show()
data = np.genfromtxt('tmp.dat', delimiter = ' ')
plt.bar(data[:,0], data[:,1], color='g')
plt.ylabel('Frequency')
plt.xlabel('Length')
plt.title('Title')
plt.show()