【问题标题】:Is there a way to return same length arrays in numpy.hist?有没有办法在 numpy.hist 中返回相同长度的数组?
【发布时间】:2013-07-31 17:24:42
【问题描述】:

我正在尝试在 python 中创建一个直方图,使用一些自定义值对 y 轴值进行归一化。为此,我想这样做:

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('foo.bar')
fig = plt.figure()
ax = fig.add_subplot(111)

hist=np.histogram(data, bins=(1.0, 1.5 ,2.0,2.5,3.0))
x=[hist[0]*5,hist[1]]
ax.plot(x[0], x[1], 'o')

当然,最后一行给出:

ValueError: x and y must have same first dimension

有没有办法强制 np.hist 为 x[0] 和 x[1] 数组提供相同数量的元素,例如删除其中一个的第一个或最后一个元素?

【问题讨论】:

    标签: python arrays numpy plot histogram


    【解决方案1】:

    hist[1] 包含您制作直方图的范围。我猜你可能想得到这些区间的中心,比如:

    x = [hist[0], 0.5*(hist[1][1:]+hist[1][:-1])]
    

    然后剧情应该没问题吧?

    【讨论】:

    • 太好了,正是我需要的!
    【解决方案2】:

    我想这取决于您的数据源。

    尝试将数据加载为 numpy 数组,并在传递给直方图函数之前自行选择元素范围。

    例如

    dataForHistogram = data[0:100][0:100]   # Assuming your data is in this kind of structure.
    

    【讨论】:

    • 我的数据文件只有一列,我想从中制作直方图。这与数据本身的限制无关,但问题在于 np.histogram 为您提供了 bin 边缘和每个边缘的数量计数,从而导致数组中包含一个额外的元素,其中包含 bin 限制。
    猜你喜欢
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多