如何在matplotlib中绘制具有相同分档宽度的直方图,以获得不等间距的分档

时间:2014-03-17 17:37:01

标签: 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)

结果如下:

Histogram with unequally spaced bins

如何摆脱两个系列中两个相应分档之间的差距?即如何为每个箱子分组不同系列的栏?

由于

1 个答案:

答案 0 :(得分: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))

hist