如何使用Python在直方图中为变量bin范围获得相同的bin宽度?

时间:2018-01-12 18:52:31

标签: python numpy matplotlib histogram data-visualization

我正在尝试使用自定义bin范围创建直方图。但是,正如您在下面的直方图中看到的那样,bin宽度不是常量。

enter image description here

理想情况下,我想要这样的东西。箱之间的间距并不重要,我只想让每个箱/列的宽度相同:

enter image description here

我用来生成第一个直方图的代码是:

plt.figure()
weights = np.ones_like(data)/float(len(data))
plt.hist(data, bins=[0, 1.0, 3.0, 5.0, 10.0, 25.0, 90.0], weights=weights) 

1 个答案:

答案 0 :(得分:2)

我认为直方图不是你想要的。通常,直方图具有连续的x轴,在示例中,您显示a轴值是分类的。在这种情况下,我建议先对数据进行分箱并先获取bin计数。然后绘制条形图。像这样:

data = np.random.randint(0, 90, 500)
bins = np.array([1,3,5,10,25,90])
digitized = np.digitize(data, bins)
counts = np.bincount(digitized)
fig, ax = plt.subplots()
ax.bar(np.arange(counts.size), counts)
ax.set_xticklabels(['', '0\N{DEGREE SIGN} - 1\N{DEGREE SIGN}', '1\N{DEGREE SIGN} - 3\N{DEGREE SIGN}', '3\N{DEGREE SIGN} - 5\N{DEGREE SIGN}', '5\N{DEGREE SIGN} - 10\N{DEGREE SIGN}', '10\N{DEGREE SIGN} - 25\N{DEGREE SIGN}', '> 25\N{DEGREE SIGN}'])
fig.show()

enter image description here