简体   繁体   中英

How to draw histogram with same bins width for unequally spaced bins in matplotlib

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

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)

The result is this:

具有不等间隔箱的直方图

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

Thanks

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

HIST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM