我正在尝试对包含 float 的文本文件制作直方图:
import matplotlib.pyplot as plt
c1_file = open('densEst1.txt','r')
c1_data = c1_file.read().split()
c1_sum = float(c1_data.__len__())
plt.hist(c1_data)
plt.show()
c1_data.__len__()
的输出工作正常,但 hist()
抛出:
C:\Python27\python.exe "C:/x.py"
Traceback (most recent call last):
File "C:/x.py", line 7, in <module>
plt.hist(c1_data)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 2958, in hist
stacked=stacked, data=data, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
return func(ax, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes\_axes.py", line 5995, in hist
if len(xi) > 0:
TypeError: len() of unsized object
最佳答案
plt.hist
调用失败的主要原因是参数 c1_data
是一个包含字符串的列表。当您打开
一个文件并阅读
它时the result will be a string包含文件内容:
To read a file’s contents, call
f.read(size)
, which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode).
强调我的。
当你现在split
这个长字符串你会得到一个包含字符串的列表:
Return a list of the words in the string, using sep as the delimiter string.
然而,字符串列表不是 plt.hist
的有效输入:
>>> import matplotlib.pyplot as plt
>>> plt.hist(['1', '2'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 import matplotlib.pyplot as plt
----> 2 plt.hist(['1', '2'])
C:\...\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs)
3079 histtype=histtype, align=align, orientation=orientation,
3080 rwidth=rwidth, log=log, color=color, label=label,
-> 3081 stacked=stacked, data=data, **kwargs)
3082 finally:
3083 ax._hold = washold
C:\...\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1895 warnings.warn(msg % (label_namer, func.__name__),
1896 RuntimeWarning, stacklevel=2)
-> 1897 return func(ax, *args, **kwargs)
1898 pre_doc = inner.__doc__
1899 if pre_doc is None:
C:\...\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***)
6178 xmax = -np.inf
6179 for xi in x:
-> 6180 if len(xi) > 0:
6181 xmin = min(xmin, xi.min())
6182 xmax = max(xmax, xi.max())
TypeError: len() of unsized object
解决方案:
您可以简单地将其转换为 float 组:
>>> import numpy as np
>>> plt.hist(np.array(c1_data, dtype=float))
关于split() 数据的 Python 直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953906/