如何在matplotlib中为不等间距的bin绘制具有相同bin宽度的直方图 [英] How to draw histogram with same bins width for unequally spaced bins in matplotlib

查看:421
本文介绍了如何在matplotlib中为不等间距的bin绘制具有相同bin宽度的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在matplotlib中绘制具有多个数据序列的直方图.

I am trying to draw a histogram with multiple data series in matplotlib.

我有不等间距的垃圾箱,但是我希望每个垃圾箱都具有相同的宽度.因此,我以这种方式使用了width属性:

I have unequally spaced bins, however I want that each bin get the same width. So I used attribute width in this way:

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.如何为每个垃圾箱分组不同系列的条形?

How can I get rid of the margin between two correspondent bins of the two series? I.e. how can I group for each bin the bars of the different series?

谢谢

推荐答案

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

a solution can be to compute the histogram by numpy and plot the bars individually by hand:

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))

这篇关于如何在matplotlib中为不等间距的bin绘制具有相同bin宽度的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆