【问题标题】:TypeError when plotting histogram with Matplotlib使用 Matplotlib 绘制直方图时出现 TypeError
【发布时间】:2018-02-22 18:26:44
【问题描述】:

我正在尝试绘制浮点数文件的直方图。文件内容如下所示:

0.1066770707640915
0.0355590235880305
0.0711180471760610
0.4267082830563660
0.0355590235880305
0.1066770707640915
0.0698755355867468
0.0355590235880305
0.0355590235880305
0.0355590235880305
0.0355590235880305
0.0355590235880305
0.2844721887042440
0.0711180471760610
0.0711180471760610
0.0355590235880305
0.0355590235880305
0.1422360943521220
0.0355590235880305
0.0355590235880305
0.0711180471760610
0.0355590235880305
0.0355590235880305
0.0355590235880305
...

出于某种原因,我的尝试是给我一个TypeError: len() of unsized object

import matplotlib.pyplot as plt

input_file = "inputfile.csv"
file = open(input_file, "r")
all_lines = list(file.readlines())
file.close()

for line in all_lines:
    line = float(line.strip()) # Removing the '\n' at the end and converting to float
    if not isinstance(line, float): # Verifying that all data points could be converted to float
        print type(line)

print len(all_lines)
# 146445

print type(all_lines)
# <type 'list'>

plt.hist(all_lines, bins = 10) # This line throws the error
plt.show()

我已经搜索过类似的问题。尝试绘制非数字数据类型时,此错误似乎很常见,但此处并非如此,因为我明确检查了每个数字的数据类型以确保它们不是奇怪的数据类型。

我有什么明显的遗漏吗?

【问题讨论】:

    标签: python python-2.7 matplotlib histogram


    【解决方案1】:

    您的循环实际上并没有将all_lines 的项目原地转换为浮点数;它只是获取每个项目,将其转换为浮点数并打印它,但它不会更改列表中的值。因此,当您绘制all_lines 时,线条仍然存储为字符串。

    您可以改为使用列表推导将列表中的所有值更改为浮点数,如下所示:

    all_lines = [float(line) for line in all_lines]
    

    更好的办法可能是使用numpy 读取文件,然后您会将这些行作为浮点数存储在一个numpy 数组中,从而省去遍历文件行的麻烦:

    import numpy as np
    import matplotlib.pyplot as plt
    
    input_file = "inputfile.csv"
    all_lines = np.genfromtxt(input_file)
    
    plt.hist(all_lines, bins = 10)
    plt.show()
    

    【讨论】:

    • 谢谢,这是一个非常愚蠢的错误。出于某种原因,np.genfromtxt() 对我不起作用,但您确实指出了错误,所以我能够修复它。
    • @Antimony:嗯,好的,很高兴它的排序。所以我可以清理答案,请问genfromtxt解决方案有什么问题?
    • 与问题无关。在第一行的开头有一些奇怪的不可见字符(我在循环中处理这些字符,这就是列表理解也不起作用的原因),我相信它们会出错genfromtxt
    • 嗯,好的,谢谢,所以解决方案代表文件结构的一般情况,就像您在问题中遇到的那样。
    • 是的,该解决方案可能适用于一般情况。我只是无法用我的文件测试它:)
    猜你喜欢
    • 2016-06-09
    • 2015-10-25
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多