Folded Bar Graph of Grouped Values ​​in Pandas

I am trying to create a complex histogram of grouped values ​​using this code:

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

But I get this histogram without stacked bars.

enter image description here

How can I compile a histogram column without using matplotlib directly or iterating over groups?

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

+6
source share
3 answers

The best way I've found so far is to create a new data file with 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

+2
source

This solution uses a bar chart 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

+3
source

I defined a custom function that uses np.histogram
Also note that histogram groups are computed inside the 'Survived' groups

 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

+2
source

Source: https://habr.com/ru/post/1014034/


All Articles