条形宽度相等的matplotlib直方图

时间:2019-10-01 11:23:38

标签: matplotlib

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

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

1 个答案:

答案 0 :(得分:0)

我无法将您的问题标记为重复,但是我认为my answer to this question可能就是您想要的?


我不确定您如何看待结果,但是您可以使用numpy.histogram计算条形图的高度,然后将它们直接绘制在任意x刻度上。

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

enter image description here


编辑:这里是对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]

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

enter image description here