Pandas 中分组值的堆叠直方图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41622054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:46:06  来源:igfitidea点击:

Stacked histogram of grouped values in Pandas

pythonpandashistogram

提问by leokury

i am trying to create a stacked histogram of grouped values using this code:

我正在尝试使用以下代码创建分组值的堆叠直方图:

titanic.groupby('Survived').Age.hist(stacked=True)

But I am getting this histogram without stacked bars.

但是我得到的这个直方图没有堆叠的条形图。

enter image description here

在此处输入图片说明

How can i get the histogram's bar stacked without having to use matplotlib directly or iterating over groups?

如何在无需直接使用 matplotlib 或迭代组的情况下堆叠直方图的条形?

Dataset used: https://www.udacity.com/api/nodes/5454512672/supplemental_media/titanic-datacsv/download

使用的数据集:https: //www.udacity.com/api/nodes/5454512672/supplemental_media/titanic-datacsv/download

采纳答案by Qianbo Wang

Improve the answer, the best way could be:

改进答案,最好的方法可能是:

titanic.pivot(columns='Survived').Age.plot(kind = 'hist', stacked=True)

enter image description here

在此处输入图片说明

回答by leokury

The best way that I found so far is to create a new dataframe with the groups:

到目前为止,我发现的最好方法是使用组创建一个新的数据框:

pd.DataFrame({'Non-Survivors': titanic.groupby('Survived').get_group(0).Age,
              'Survivors':   titanic.groupby('Survived').get_group(1).Age})
            .plot.hist(stacked=True)

enter image description here

在此处输入图片说明

回答by Ted Petrou

This solution uses a bar plot instead of a histogram but I think it gives you what you are looking for.

此解决方案使用条形图而不是直方图,但我认为它可以为您提供所需的内容。

titanic.groupby(['Survived', pd.cut(titanic['Age'], np.arange(0,100,10))])\
       .size()\
       .unstack(0)\
       .plot.bar(stacked=True)

enter image description here

在此处输入图片说明

回答by piRSquared

I defined a custom function that leverages np.histogram
Also note that the histogram groups are calculated within groups of 'Survived'

我定义了一个利用的自定义函数np.histogram
另请注意,直方图组是在以下组内计算的'Survived'

def hist(x):
    h, e = np.histogram(x.dropna(), range=(0, 80))
    e = e.astype(int)
    return pd.Series(h, zip(e[:-1], e[1:]))

kw = dict(stacked=True, width=1, rot=45)
titanic.groupby('Survived').Age.apply(hist).unstack(0).plot.bar(**kw)

enter image description here

在此处输入图片说明