Python:如何根据数字数组绘制CDF函数
我在使用Windows系统。我只是想输入一个数组,然后得到这个数组的累积分布函数(cdf)。
2 个回答
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()
5
首先,你可以这样实现累积分布函数(CDF):
from bisect import bisect_left
class discrete_cdf:
def __init__(self, data):
self._data = data # must be sorted
self._data_len = float(len(data))
def __call__(self, 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的值都是一样的。