分布直方图中的加权箱

Weighted bins in a distribution hist plot

我正在寻找一种绘制分布直方图的方法,y-axis 代表每个 bin 的项目总数(而不仅仅是计数)。

下表示例:

这并不像看起来那么微不足道,因为不能简单地将每个箱子的数量乘以箱子的价值(也许在 20-30 箱子中,有 54 个机构售出 21 个,1 个机构售出 29 个)。

问题:

您想使用 weights kwarg(参见 numpy docs) which is passed through ax.hist (see)。

类似

fig, ax = plt.subplots()
ax.hist(num_sold, bins, weights=num_sold)

编辑:@tacaswell 最好使用它。但是我的标签会毫不费力地正确排列,并且条会分开。

希望您的数据在 pandas。我会创建一些假数据,然后给你一个解决方案。

import pandas as pd

# create a dataframe of number of homes sold
df = pd.DataFrame(data={'sold':np.random.randint(0,100, 1000)})

# groupby the left side of interval [0, 10), [10, 20) etc..  and plot
df.groupby(df.sold // 10 * 10).sum().plot.bar()