如何绘制从 numpy.hist 返回的直方图数据?

how to plot histogram data returned from numpy.hist?

我使用 numpy.histogram 创建了多个直方图,但在绘制它们时遇到了问题。 我的代码基本上是:

hist_data, bin_edges = np.histogram(pw_dist, 10, (0, limit + 1), None, weights)
#perform some logic on histogram data
plt.hist(hist_data, bins=bin_edges)

hist_data 是 ([ 0., 0., 1176., 576., 2628., 1680., 2952., 3312., 3444., 2904.])

和bin_edges是:([ 0. , 1.6, 3.2, 4.8, 6.4, 8. , 9.6, 11.2, 12.8, 14.4, 16. ])

这很好,但是,当尝试使用 plt.hist 绘制它时,我得到的是: Histogram of above hist_data and bin_edges 这与 hist_data 数组中的值并不真正对应。 所以 TLDR,给定直方图 data/bins 数组,如何使用 matplotlib.pyplot hist 函数正确绘制直方图?

plt.bar怎么样?

hist_data, bin_edges = np.histogram(pw_dist, 10, (0, limit + 1), None, weights)

# Plot the histogram
fig, ax = plt.subplots()
ax.bar(bin_edges[:-1], hist_data, width=np.diff(bin_edges))

请注意,我们通过计算 bin_edges 中相邻元素的差异来计算 bin 的宽度。

matplotlib hist 函数将原始数据作为输入,因此您也可以尝试plt.hist(pw_dist) 快速绘制直方图。