2011-05-27 155 views
3

我正在使用Windows。我只想输入数组并获取数组的cdf。Python:如何绘制一个给定数组数组的cdf函数

+0

你有Matplotlib和numpy/scipy吗? – 2011-05-27 08:49:57

+0

@ Space_C0wb0y:是 – Bruce 2011-05-27 09:09:31

+0

@Bruce:另外,你的意思是* cdf的数组* *? cdf必须根据某个分布进行计算。 – 2011-05-27 09:25:58

回答

3

首先,可以实现CDF这样的:

from bisect import bisect_left 

class discrete_cdf: 
    def __init__(data): 
     self._data = data # must be sorted 
     self._data_len = float(len(data)) 

    def __call__(point): 
     return (len(self._data[:bisect_left(self._data, point)])/
       self._data_len) 

使用上述类,则可以这样绘图:

from scipy.stats import norm 
import matplotlib.pyplot as plt 

cdf = discrete_cdf(your_data) 
xvalues = range(0, max(your_data)) 
yvalues = [cdf(point) for point in xvalues] 
plt.plot(xvalues, yvalues) 

编辑:arange在这里没有意义,对于x和x + 1之间的所有点,cdf将始终相同。

+0

不错的解决方案。您可以将len(self._data [:bisect_left(self._data,point)])'简化为'bisect_left(self._data,point)',因为slice已经指定了长度。也许'bisect_right'也会更好,因为CDF是用于P(X <= x)的点。 – 2012-03-14 06:08:38

2

这是你在追求什么? 我提供了一个函数来近似cdf并绘制它。 (假设要输入与y值的PDF阵列)

import matplotlib.pyplot as plt 
from math import exp 

xmin=0 
xmax=5 
steps=1000 
stepsize=float(xmax-xmin)/float(steps) 
xpoints=[i*stepsize for i in range(int(xmin/stepsize),int(xmax/stepsize))] 
print xpoints,int(xmin/stepsize),int(xmax/stepsize) 

ypoints=map(lambda x: exp(-x),xpoints) 

def get_cdf(pdf_array): 
    ans=[0] 
    for i in range(0,len(pdf_array)-1): 
     ans.append(ans[i]+(pdf_array[i]+pdf_array[i+1])/2.0*stepsize) 
    return ans 

cdfypoints=get_cdf(ypoints) 

plt.plot(xpoints,ypoints) 
plt.plot(xpoints,cdfypoints) 
plt.show() 

enter image description here

相关问题