条形宽度相等的matplotlib直方图 [英] matplotlib histogram with equal bars width

查看:55
本文介绍了条形宽度相等的matplotlib直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用直方图来显示分布.如果垃圾箱的间距是均匀的,则一切正常.但是如果间隔不同,那么条形宽度是合适的(如预期的那样).有没有办法独立于 bin 的大小设置条的宽度?

<小时>

编辑 这是对 x-tick 标签的调整,以便更容易看到对应关系.

my_bins = [10, 20, 30, 40, 50, 120]my_data = [5, 5, 6, 8, 9, 15, 25, 27, 33, 45, 46, 48, 49, 111, 113]无花果= plt.figure()ax = fig.add_subplot(211)ax.hist(my_data, bins=my_bins, edgecolor='k')ax = fig.add_subplot(212)h,e = np.histogram(my_data, bins=my_bins)ax.bar(range(len(my_bins)-1),h,width = 1,edgecolor ='k')ax.set_xticks(范围(len(my_bins)-1))ax.set_xticklabels(my_bins [:-1])

I use a histogram to display the distribution. Everything works fine if the spacing of the bins is uniform. But if the interval is different, then the bar width is appropriate (as expected). Is there a way to set the width of the bar independent of the size of the bins ?

This is what i have

This what i trying to draw

from matplotlib import pyplot as plt

my_bins = [10, 20, 30, 40, 50, 120]
my_data = [5, 5, 6, 8, 9, 15, 25, 27, 33, 45, 46, 48, 49, 111, 113]

fig1 = plt.figure()

ax1 = fig1.add_subplot(121)
ax1.set_xticks(my_bins)
ax1.hist(my_data, my_bins, histtype='bar', rwidth=0.9,)
fig1.show()

解决方案

I cannot mark your question as a duplicate, but I think my answer to this question might be what you are looking for?


I'm not sure how you'll make sense of the result, but you can use numpy.histogram to calculate the height of your bars, then plot those directly against an arbitrary x-scale.

x = np.random.normal(loc=50, scale=200, size=(2000,))
bins = [0,1,10,20,30,40,50,75,100]
fig = plt.figure()
ax = fig.add_subplot(211)
ax.hist(x, bins=bins, edgecolor='k')
ax = fig.add_subplot(212)
h,e = np.histogram(x, bins=bins)
ax.bar(range(len(bins)-1),h, width=1, edgecolor='k')


EDIT Here's with the adjustment to the x-tick labels so that the correspondence is easier to see.

my_bins = [10, 20, 30, 40, 50, 120]
my_data = [5, 5, 6, 8, 9, 15, 25, 27, 33, 45, 46, 48, 49, 111, 113]

fig = plt.figure()
ax = fig.add_subplot(211)
ax.hist(my_data, bins=my_bins, edgecolor='k')
ax = fig.add_subplot(212)
h,e = np.histogram(my_data, bins=my_bins)
ax.bar(range(len(my_bins)-1),h, width=1, edgecolor='k')
ax.set_xticks(range(len(my_bins)-1))
ax.set_xticklabels(my_bins[:-1])

这篇关于条形宽度相等的matplotlib直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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