Plotting a dataframe as both a 'hist' and 'kde' on the same plot
<p>I have a pandas <code>dataframe</code> with user information. I would like to plot the age of users as both a <code>kind='kde'</code> and on <code>kind='hist'</code> on the same plot. At the moment I am able to have the two separate plots. The dataframe resembles:</p>

<pre><code>member_df=    
user_id    Age
1          23
2          34
3          63 
4          18
5          53  
...
</code></pre>

<p>using </p>

<pre><code>ax1 = plt.subplot2grid((2,3), (0,0))
member_df.Age.plot(kind='kde', xlim=[16, 100])
ax1.set_xlabel('Age')

ax2 = plt.subplot2grid((2,3), (0,1))
member_df.Age.plot(kind='hist', bins=40)
ax2.set_xlabel('Age')

ax3 = ...
</code></pre>

<p>I understand that the <code>kind='kde'</code> will give me frequencies for the y-axis whereas  <code>kind='kde'</code> will give a cumulative distribution, but is there a way to combine both and have the y-axis be represented by the frequencies?</p>

<p><code>pd.DataFrame.plot()</code> returns the <code>ax</code> it is plotting to.  You can reuse this for other plots.</p>

<p>Try:</p>

<pre><code>ax = member_df.Age.plot(kind='kde')
member_df.Age.plot(kind='hist', bins=40, ax=ax)
ax.set_xlabel('Age')
</code></pre>

<p><strong><em>example</em></strong><br>
I plot <code>hist</code> first to put in background<br>
Also, I put <code>kde</code> on <code>secondary_y</code> axis  </p>

<pre><code>import pandas as pd
import numpy as np


np.random.seed([3,1415])
df = pd.DataFrame(np.random.randn(100, 2), columns=list('ab'))

ax = df.a.plot(kind='hist')
df.a.plot(kind='kde', ax=ax, secondary_y=True)
</code></pre>

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

<hr>

<p><strong><em>response to comment</em></strong><br>
using <code>subplot2grid</code>.  just reuse <code>ax1</code></p>

<pre><code>import pandas as pd
import numpy as np

ax1 = plt.subplot2grid((2,3), (0,0))

np.random.seed([3,1415])
df = pd.DataFrame(np.random.randn(100, 2), columns=list('ab'))

df.a.plot(kind='hist', ax=ax1)
df.a.plot(kind='kde', ax=ax1, secondary_y=True)
</code></pre>

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

python pandas matplotlib plot