【问题标题】:change the count in a Python histogram bin更改 Python 直方图 bin 中的计数
【发布时间】:2013-10-08 23:21:31
【问题描述】:

我有一个 Python 直方图。

我想将直方图的峰值标准化为 1,这样只有条形的相对高度很重要。

我看到了一些涉及更改 bin 宽度的方法,但我不想这样做。

我也意识到我可以只更改 y 轴的标签,但我还覆盖了另一个图,所以 yticks 必须是实际值。

有没有办法访问和更改每个 bin 中的直方图“计数”?

谢谢。

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    我认为您所追求的是直方图的标准化形式,其中 y 轴是密度而不是计数。如果您使用的是 Numpy,只需在 histogram function 中使用 normed 标志。

    如果您希望直方图的峰值为 1,则可以将每个 bin 中的计数除以最大 bin 值,即(构建 SO MatPlotLib 示例 here):

    #!/usr/bin/env python
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate random data
    mu, sigma = 200, 25
    x = mu + sigma*np.random.randn(10000)
    
    # Create the histogram and normalize the counts to 1
    hist, bins = np.histogram(x, bins = 50)
    max_val = max(hist)
    hist = [ float(n)/max_val for n in hist]
    
    # Plot the resulting histogram
    center = (bins[:-1]+bins[1:])/2
    width = 0.7*(bins[1]-bins[0])
    plt.bar(center, hist, align = 'center', width = width)
    plt.show()
    

    【讨论】:

    • 但这不是将面积归一化为 1 而不是峰值吗?
    • 是的,完全正确。但它应该让您足够轻松地比较条形的相对高度。如果您确实希望峰值为 1,只需将每个 bin 除以最大 bin 的值即可。
    • 对不起,如果我很笨,但这是我的问题。我不知道如何将垃圾箱除以某个值。
    • 我修改了我的答案以显示如何将 bin 除以最大 bin 值。
    • 我修改了示例以包括生成直方图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多