【问题标题】:How to create a Histogram in python from a histogram source file如何从直方图源文件在python中创建直方图
【发布时间】:2021-03-17 08:54:43
【问题描述】:

我想从 python 中的两个列表重新创建一个直方图。我是编程新手,但我需要它来进行研究中的数据分析。我在一个列表和另一个具有指定计数的列表中有一些关于测量高度值的数据。例如。 :

height = [0, 2, 4, 6, 8, 10]
count = [294, 420, 410, 2000, 400, 200]

如何从这两个列表创建直方图?我很确定,一定有一个简单的方法可以做到这一点,但我还没有弄清楚。我需要python中的直方图的原因是因为我必须拟合一个高斯,这应该没问题,但是没有归一化的直方图就没用了。 我的第一个意图是使用:

matplotlib.pyplot.hist([height, count])

但它显然产生了两个直方图。

感谢您的回答

【问题讨论】:

    标签: python histogram data-analysis


    【解决方案1】:

    我认为您希望数据集使用条形图。

    import matplotlib.pyplot as plt
    
    height = [0, 2, 4, 6, 8, 10]
    count = [294, 420, 410, 2000, 400, 200]
    
    fig, ax = plt.subplots()
    ax.bar(height, count, width=1.6)
    
    plt.show()
    

    请注意,我在ax.bar 中使用了width 关键字参数来设置条的宽度。默认为0.8,如果你想让bar条相互连接,可以设置为2

    【讨论】:

    • 感谢您的回答。如果只是为了表示数据,我会同意您的看法,但对于高斯拟合,我更喜欢在 hist 函数中使用密度参数。
    • 您可以使用密度值之和(乘以条形宽度)为 1 的属性简单地将计数转换为密度值。因此,您可以手动计算 density = [val / sum(count) / barwidth for val in count]barwidth = 2 在你的情况下。
    • 谢谢,这改变了游戏规则。对于学习贡献,我会尝试这两种方法
    【解决方案2】:

    Matplotlib 的 hist 方法需要一个值列表。它自己计算计数。因此,一种解决方案是生成适合您的模型的数据:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import matplotlib.pyplot as plt
    
    # 1. count will be the height of the bars and height the width
    height = [0, 2, 4, 6, 8, 10]
    count = [294, 420, 410, 2000, 400, 200]
    
    # 2. create an empty list
    #    and add 294 times 0, 420 times 2, and so on...
    #    so eventually values will look something like [0, 0, ..., 2, 2, ... 10, 10]
    values=[]
    for i in range(6): # len(height) or len(count) assuming the two are equal
        values += ([height[i]] * count[i])
    
    plt.figure()
    plt.hist(values, bins=range(-1, 12, 2)) # define bin limits
    plt.show()
    

    这给你:

    【讨论】:

    • 请注意,直方图中的条形与 height 值不匹配:第一个条跨越 x 值,范围从 0 到 5/3,第二个条跨越 5/3 到 10/3等。
    • 非常感谢,这正是我想要的。我还考虑过(并尝试过)创建一个包含这些重复值的列表,但失败了。这也只是一个例子,我有 2 乘以 200 的数据值,可以玩分箱。
    • @luuk 你是对的,我强制了 bin 限制,所以现在应该会更好
    • 您现在只显示 5 个 bin,它们在高度值之间居中。正确的范围是range(-1, 12, 2) (range(min(height) - binwidth / 2, max(height) + binwidth / 2 + 1, binwidth)),但对于非恒定的 bin 宽度,需要一种更复杂的方法。
    • 哦,太好了,这样标签也可以居中。谢谢!
    猜你喜欢
    • 2017-07-27
    • 2022-01-21
    • 1970-01-01
    • 2021-05-15
    • 2012-03-30
    • 1970-01-01
    • 2011-06-21
    • 2018-04-16
    相关资源
    最近更新 更多