如何在 matplotlib 中为不等间距的 bin 绘制具有相同 bin 宽度的直方图

gc5*_*gc5 6 python matplotlib histogram

我正在尝试在 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)
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

具有不等间距箱的直方图

如何消除两个系列的两个对应箱之间的边距?即,如何为每个箱中不同系列的条形图进行分组?

谢谢

beh*_*uri 3

一种解决方案是通过 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))
Run Code Online (Sandbox Code Playgroud)

历史

  • @unsel我想你对浮动除法是正确的;我在 python 2.7 上运行了这个;但这对我有用,因为我的脚本顶部总是有“from __future__ import division”。 (2认同)