In the ax.hist文档中,有一个相关的重用示例np.histogram output:
The weights
参数可用于绘制已分箱的数据的直方图,方法是将每个箱视为权重等于其计数的单个点。
counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)
我们可以使用相同的方法ax.hist因为它还返回计数和垃圾箱(以及条形容器):
x = np.random.default_rng(123).integers(10, size=100)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3))
counts, bins, bars = ax1.hist(x) # original hist
ax2.hist(bins[:-1], bins, weights=counts) # rebuilt via weights params
![rebuilt via weights param](https://i.stack.imgur.com/Nfjuc.png)
或者,使用重建原始直方图ax.bar并重新设置宽度/对齐方式以匹配ax.hist:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3))
counts, bins, bars = ax1.hist(x) # original hist
ax2.bar(bins[:-1], counts, width=1.0, align='edge') # rebuilt via ax.bar
![rebuilt via ax.bar](https://i.stack.imgur.com/kNJPw.png)