【问题标题】:How to draw histogram with same bins width for unequally spaced bins in matplotlib如何在 matplotlib 中为不等间距的 bin 绘制具有相同 bin 宽度的直方图
【发布时间】:2014-03-17 17:37:01
【问题描述】:

我正在尝试在 matplotlib 中绘制包含多个数据系列的直方图。

我有不等间距的箱子,但是我希望每个箱子都具有相同的宽度。所以我这样使用属性width

aa = [0,1,1,2,3,3,4,4,4,4,5,6,7,9]
plt.hist([aa, aa], bins=[0,3,9], width=0.2)

结果是这样的:

我怎样才能摆脱两个系列的两个通讯箱之间的边距? IE。如何为每个 bin 对不同系列的条进行分组?

谢谢

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    一种解决方案可以是通过 numpy 计算直方图并手动绘制条形:

    aa1 = [0,1,1,2,3,3,4,4,5,9]
    aa2 = [0,1,3,3,4,4,4,4,5,6,7,9]
    bins = [0,3,9]
    height = [np.histogram( xs, bins=bins)[0] for xs in [aa1, aa2]]
    left, n = np.arange(len(bins)-1), len(height)
    
    ax = plt.subplot(111)
    color_cycle = ax._get_lines.color_cycle
    
    for j, h in enumerate(height):
        ax.bar(left + j / n, h, width=1.0/n, color=next(color_cycle))
    
    ax.set_xticks(np.arange(0, len(bins)))
    ax.set_xticklabels(map(str, bins))
    

    【讨论】:

    • 不错的解决方案.. 我稍等一下就知道是否有内置的东西。暂时 +1
    • width 可以是一个数组。我读到的问题是希望条形图的宽度适合 bin 宽度......
    • 因为没有其他答案,所以接受。请注意,此解决方案仅适用于 Python 3+,因为在计算 ax.bar() 调用中的偏移量时存在隐式浮点除法。考虑添加 float(j) 演员表,使其对 Python 2 也有用。谢谢
    • @unsel 我猜你对浮点除法是正确的;我在 python 2.7 上运行它;但它对我有用,因为我的脚本上总是有from __future__ import division