【问题标题】:Python histogram of split() datasplit() 数据的 Python 直方图
【发布时间】:2017-05-13 13:48:36
【问题描述】:

我正在尝试在包含浮点数的文本文件上制作直方图:

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

【问题讨论】:

  • 您的数据看起来如何?
  • 计算单个数字的直方图没有意义。请提供完整的问题描述,包括您要达到的目标。见How to Askminimal reproducible example
  • @ImportanceOfBeingErnest 为什么你会认为它是一个数字?
  • 正如我所说,它是一个包含浮点数的文本文件 :) 以空格分隔

标签: python matplotlib split histogram


【解决方案1】:

plt.hist 调用失败的主要原因是参数c1_data 是一个包含字符串的列表。当你open 一个文件和readthe result will be a string 包含文件内容:

要读取文件的内容,请调用f.read(size),它会读取一定数量的数据并返回作为字符串(在文本模式下)或字节对象(在二进制模式下)。

强调我的。

当你现在split这个长字符串时,你会得到一个包含字符串的列表:

返回字符串中的单词列表,使用 sep 作为分隔符字符串。

但是,字符串列表不是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

解决办法:

您可以简单地将其转换为浮点数组:

>>> import numpy as np
>>> plt.hist(np.array(c1_data, dtype=float))

【讨论】:

  • 谢谢。没有仔细阅读 split() 的文档,并认为它已经将它们投射了
  • @Yannik 不客气。您也可以尝试使用np.loadtxtc1_data = np.loadtxt('densEst1.txt')。它可能需要对参数进行一些摆弄,但是当它工作时,它会自动读取文件,将其拆分并将其转换为数组。 :) 但我不知道您的数据集是什么样子(一行包含值,或每行一个值或完全其他内容),这就是为什么我没有将它包含在答案中。
【解决方案2】:

使用 numpy 指向一个示例 ... 很简单,结果如下所示。

pandas 也可以,在读取时可以使用拆分和数据类型(即使是列数据),也可以读取为 vector(取决于数据大小)/

# !/usr/bin/env python
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np

# will be better to read with numpy because you use float ...
#a = np.fromfile(open('from_file', 'r'), sep='\n') 

from_file = np.array([1, 2, 2.5]) #sample data a
c1_data = from_file.astype(float) # convert the data in float

plt.hist(c1_data)  # plt.hist passes it's arguments to np.histogram
plt.title("Histogram without 'auto' bins")
plt.show()

plt.hist(c1_data, bins='auto')  # plt.hist passes it's arguments to np.histogram
plt.title("Histogram with 'auto' bins")
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2014-12-03
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多