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
Stacked histogram of grouped values in Pandas
提问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.
但是我得到的这个直方图没有堆叠的条形图。
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
回答by leokury
回答by Ted Petrou
回答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)