Python stacked histogram grouped data
<p>How can I create a stacked Histogram like this:
<a href="http://i.stack.imgur.com/vVKq3.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vVKq3.jpg" alt="enter image description here"></a></p>

<pre><code>import numpy as np
import pylab as P
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')

%pylab inline
pylab.rcParams['figure.figsize'] = (15, 4)
mu, sigma = 200, 25
x = mu + sigma*P.randn(1000,2)
n, bins, patches = P.hist(x, 10, normed=1, histtype='bar', stacked=True)
P.show()
</code></pre>

<p>For grouped data.</p>

<pre><code>import pandas as pd
df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,1]})
</code></pre>

<p>As
<code>df1.A.hist(by=df1.group, bins='doane', stacked=True)</code> or</p>

<pre><code>df1.A.hist(by=df1.group, bins='doane')
</code></pre>

<p>only result in:
<a href="http://i.stack.imgur.com/x8rEK.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/x8rEK.jpg" alt="enter image description here"></a></p>

<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a> your DataFrame so that each group is in a different column and then generate the histogram.</p>

<pre><code>df1 = pd.DataFrame({'A': [1,2,3,4,5,6,7,8,9],'group': [1,0,0,0,0,1,1,1,1]})
df1.pivot(columns='group', values='A').plot.hist(stacked=True)
</code></pre>

<p><a href="http://i.stack.imgur.com/Rzt52.png" rel="nofollow"><img src="http://i.stack.imgur.com/Rzt52.png" alt="enter image description here"></a></p>

<p>Edit: Added the <code>stacked=True</code> parameter to <code>hist()</code></p>

python pandas plot visualization