matplotlib / pandas中是否有一个参数使直方图的Y轴为百分比?

时间:2013-07-26 06:04:59

标签: python pandas matplotlib

我想通过让Y轴显示整个数据集大小中每列的百分比而不是绝对值来比较两个直方图。那可能吗?我正在使用Pandas和matplotlib。 感谢

6 个答案:

答案 0 :(得分:51)

density=Truenormed=True的{​​{1}})会返回matplotlib < 2.2.0等于1的直方图。如果您希望直方图的总和为1,则可以使用Numpy的直方图()并自己标准化结果。

np.sum(pdf * np.diff(bins))

enter image description here

顺便说一句:奇怪的是在左图的第一个区域绘制小故障。

答案 1 :(得分:14)

Pandas plotting可以接受来自相应matplotlib函数的任何额外的关键字参数。因此,为了完整性来自其他人的评论,这就是人们如何做到的:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100,2), columns=list('AB'))

df.hist(density=1)

此外,对于直接比较,这也可能是一个好方法:

df.plot(kind='hist', density=1, bins=20, stacked=False, alpha=.5)

答案 2 :(得分:12)

看起来像@CarstenKönigfound the right way

df.hist(bins=20, weights=np.ones_like(df[df.columns[0]]) * 100. / len(df))

答案 3 :(得分:4)

您可以使用 np.ones_like()简化权重:

df["ColumnName"].plot.hist(weights = np.ones_like(df.index) / len(df.index))
  • np.ones_like()可以使用df.index结构
  • len(df.index)对于大型DataFrames来说速度更快

答案 4 :(得分:0)

我知道这个答案是6年后的事,但是对于任何使用density = True(代替normed = True)的人,这并不是您想要做的。它将对整个分布进行标准化处理,以使垃圾箱的面积为1。因此,如果您有更多宽度小于1的垃圾箱,则可以期望高度> 1(y轴)。如果要将直方图限制为[0; 1],则必须自己计算。

答案 5 :(得分:0)

我认为这是一个老问题,但它在某些搜索中显示在顶部,所以我认为从 2021 年开始,seaborn 将是一种简单的方法。

你可以这样做:

import seaborn as sns
sns.histplot(df,stat="probability")