How to extract x,y data from kdensity plot from matplotlib for python
<p>I am trying to figure out how to make a 3d figure of uni-variate kdensity plots as they change over time (since they pull from a sliding time window of data over time).  </p>

<p>Since I can't figure out how to do that directly, I am first trying to get the x,y plotting data for kdensity plots of matplotlib in python.  I hope after I extract them I can use them along with a time variable to make a three dimensional plot.  </p>

<p>I see several posts telling how to do this in Matlab. All reference getting <code>Xdata</code> and <code>Ydata</code> from the underlying figure:</p>

<pre><code>x=get(h,'Xdata')
y=get(h,'Ydata')
</code></pre>

<p>How about in python?</p>

<p>The answer was already contained in another thread (<a href="http://stackoverflow.com/questions/4150171/how-to-create-a-density-plot-in-matplotlib">How to create a density plot in matplotlib?</a>).  It is pretty easy to get a set of kdensity x's and y's from a set of data.  </p>

<pre><code>import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8 # data is a set of univariate data
xs = np.linspace(0,max(data),200) # This 200 sets the # of x (and so also y) points of the kdensity plot
density = gaussian_kde(data)
density.covariance_factor = lambda : .25 
density._compute_covariance()
ys = density(xs)
plt.plot(xs,ys)
</code></pre>

<p>And there you have it.  Both the kdensity plot and it's underlying x,y data.</p>

python matplotlib distribution