2014-10-17 52 views
0

我试图绘制直方图,但我一直在收到此错误;错误:无法使用灵活类型执行缩小

Traceback (most recent call last): 
File "<pyshell#62>", line 1, in <module> 
plt.hist(a) 
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2827, in hist 
stacked=stacked, **kwargs) 
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 8312, in hist 
xmin = min(xmin, xi.min()) 
File "/usr/lib/python2.7/dist-packages/numpy/core/_methods.py", line 21, in _amin 
out=out, keepdims=keepdims) 
TypeError: cannot perform reduce with flexible type 

我对python非常陌生,我想要做的是这样;

import numpy, matplotlib.pyplot 

line = " " 
a = [] 
b = [] 
c = [] 
alpha = [] 
beta = [] 
gama = [] 

while x.readline(): 
    line = x.readline() 
    a.append(line[16:23]) 
    b.append(line[25:32]) 
    c.append(line[27:34]) 
    alpha.append(line[40:47]) 
    beta.append(line[49:54]) 
    gama.append(line[56:63]) 

pyplot.hist(a)' 

当我运行这段代码时,我得到了那个错误。我哪里做错了?我真的很感谢帮助

回答

0

它看起来像你试图绘制直方图基于字符串,而不是数字。尝试这样的事情,而不是:

from matplotlib import pyplot 
import random 
# generate a series of numbers 
a = [random.randint(1, 10) for _ in xrange(100)] 
# generate a series of strings that look like numbers 
b = [str(n) for n in a] 

# try to create histograms of the data 
pyplot.hist(a) # it produces a histogram (approximately flat, as expected) 

pyplot.hist(b) # produces the error as you reported. 

一般来说,最好使用预先写好的图书馆阅读数据从外部文件(例如,参见numpy's genfromtxtcsv module)。 但至少,您可能需要将您读取的数据视为数字,因为readline返回字符串。例如:

for line in f.read(): 
    fields = line.strip().split() 
    nums = [int(field) for field in fields] 

现在nums为您提供该行的整数列表。

相关问题