python - matplotlib/pandas 中是否有参数将直方图的 Y 轴设为百分比?

标签 python pandas matplotlib

我想比较两个直方图,让 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()')

enter image description here

顺便说一句:左侧绘图的第一个 bin 出现奇怪的绘图故障。

关于python - matplotlib/pandas 中是否有参数将直方图的 Y 轴设为百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17874063/

相关文章:

Python:如何迭代 20 列并找到顶部列?

python - 如何使用每个向量条目来填充数据帧中单独组的 NAN

python pandas.loc 找不到行名称 : KeyError

python - 查找 map 上一条线下方的所有点

python - Pandas Dataframe 条形图 - 定性变量?

c++ - 如何使用 autotools 构建 Python C 扩展模块

python - 将模块导入 Jupyter

python - Scala 嵌套列表

python - 如何在EMR核心节点上启用python库以启动EMR Spark应用程序步骤

python - 从 Pandas 数据框中的值动画 Quiver 图