我想比较两个直方图,让 Y 轴显示每列占整个数据集大小的百分比,而不是绝对值。那可能吗?我正在使用 Pandas 和 matplotlib。 谢谢
最佳答案
density=True
( normed=True
表示 matplotlib < 2.2.0
)返回一个直方图,其中 np.sum(pdf * np.diff(bins))
等于 1。如果您希望直方图的总和为 1,您可以使用 Numpy 的 histogram() 并自己对结果进行归一化。
x = np.random.randn(30)
fig, ax = plt.subplots(1,2, figsize=(10,4))
ax[0].hist(x, density=True, color='grey')
hist, bins = np.histogram(x)
ax[1].bar(bins[:-1], hist.astype(np.float32) / hist.sum(), width=(bins[1]-bins[0]), color='grey')
ax[0].set_title('normed=True')
ax[1].set_title('hist = hist / hist.sum()')
顺便说一句:左侧绘图的第一个 bin 出现奇怪的绘图故障。
关于python - matplotlib/pandas 中是否有参数将直方图的 Y 轴设为百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17874063/