【问题标题】:Python pyplot histogram: Adjusting bin width, Not number of binsPython pyplot 直方图:调整 bin 宽度,而不是 bin 数量
【发布时间】:2015-03-22 00:04:45
【问题描述】:

我已经能够让自己看起来像这样一个漂亮的小直方图:

我能够使用以下代码生成图像:

    import numpy as np
    import matplotlib.pyplot as plt

    plt.figure()  
    plt.axis([0, 6000, 0, 45000])  

    data['column'][data.value == 0].hist(bins=200, label='A') 
    data['column2'][data.value == 1].hist(bins=200, label='B')

    plt.title('A Histogram')  
    plt.xlabel('x-axis')  
    plt.ylabel('y-axis')  
    plt.legend()  

    return plt

这一切都很好,但垃圾箱的长度不相等。我能够以相同长度获得垃圾箱的唯一方法是执行以下操作:

 bins=[0,100,200,300,400,.......)

这根本不漂亮。

我在谷歌上搜索了一下,然后环顾四周。类似问题的最受欢迎答案是this guy,这表明了一个看似出色的答案,但我无法终生工作。

感谢您的帮助!

【问题讨论】:

    标签: python matplotlib histogram bins


    【解决方案1】:

    我对您的数据结构以及您如何调用函数hist 有点困惑。但是,我假设您使用的是 matplotib,因此您需要为 hist 函数定义相同的分箱范围。如果你传递一个带有 bin 边界的数组,而不是你想要的 bin 数量,效果会更好。

    import numpy as np
    import matplotlib.pyplot as plt
    
    plt.figure()  
    plt.axis([0, 6000, 0, 45000])  
    
    # From your example I am assuming that the maximum value is 6000
    binBoundaries = np.linspace(0,6000,201)
    
    data['column'][data.value == 0].hist(bins=binBoundaries, label='A') 
    data['column2'][data.value == 1].hist(bins=binBoundaries, label='B')
    
    plt.title('A Histogram')  
    plt.xlabel('x-axis')  
    plt.ylabel('y-axis')  
    plt.legend()
    

    这应该适合你。

    如果有帮助,请告诉我。

    【讨论】:

    • 非常感谢。做到了。我以为我以前尝试过,但显然我没有。谢谢!