【问题标题】:Plotting histogram of floating point numbers and integers in python在python中绘制浮点数和整数的直方图
【发布时间】:2015-08-28 04:33:37
【问题描述】:

我有一组整数和浮点数,我想从中绘制直方图。为此,我使用以下代码:

import matplotlib.pyplot as plt
from numpy import array
gn=array([1,2,3,728,625,0,736,5243,9.0])
plt.hist(gn)
plt.show()

但是,我最终得到以下错误:

    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

我不知道我哪里出错了,有人可以建议我如何绘制浮点数和整数的直方图

【问题讨论】:

  • 这是非常奇怪的行为。正如 Amy 所说,如果您的输入列表包含浮点数和整数的组合,那么在创建数组时应该将其转换为所有浮点数。您能否确认上面的确切代码重现了该错误(在您的回溯中,您似乎使用了另一个名为 a 的变量)?你用的是什么版本的numpy? gn.dtype 是什么?
  • 会导致您看到的错误的一件事是,如果您的数组实际上包含非数字数据 (see here)

标签: python numpy matplotlib


【解决方案1】:

有趣。当我运行它时,numpy 会自动使整数浮动。必须是不同的版本。您可以使用 astype() 方法将数组从灵活数据类型更改为浮点数据类型。试试这个:

import matplotlib.pyplot as plt
from numpy import array
gn=array([1,2,3,728,625,0,736,5243,9.0])
plt.hist(gn.astype('float'))
plt.show()

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 2014-06-14
    • 1970-01-01
    • 2017-07-26
    • 2017-10-23
    • 2013-09-17
    • 2020-09-27
    • 2011-08-21
    • 1970-01-01
    相关资源
    最近更新 更多