1

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).

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.

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

x=get(h,'Xdata')
y=get(h,'Ydata')

How about in python?

dhrubo_moy
  • 1,144
  • 13
  • 31
Jeremy Schutte
  • 352
  • 1
  • 3
  • 13
  • 1
    How exactly did you generate the plot? Can you show the code you have so far? Depending on how the plot was generated there may be easier ways than getting it from the figure, although that is possible. – TheBlackCat Sep 23 '16 at 18:18
  • I was using Seaborn for the plot and tearing my hair out analyzing it's fields and methods. I found out how to do it from another post that I linked to below. – Jeremy Schutte Sep 24 '16 at 13:08

2 Answers2

1

The answer was already contained in another thread (How to create a density plot in matplotlib?). It is pretty easy to get a set of kdensity x's and y's from a set of data.

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)

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

Community
  • 1
  • 1
Jeremy Schutte
  • 352
  • 1
  • 3
  • 13
0

Not sure how kdensity plots work, but note that matplotlib.pyplot.plot returns a list of the added Line2D objects, which are, in fact, where the X and Y data are stored. I suspect they did that to make it work similarly to MATLAB.

import matplotlib.pyplot as plt

h = plt.plot([1,2,3],[2,4,6])  # [<matplotlib.lines.Line2D object at 0x021DA9F0>]
x = h[0].get_xdata()  # [1,2,3]
y = h[0].get_ydata()  # [2,4,6]
user13803
  • 95
  • 6