Python: How to plot a cdf function given an array of numbers
I am worki开发者_如何学JAVAng on Windows. I just want to input an array and get the cdf of the array.
First, you could implement the CDF like this:
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)
Using the above class, you can plot it like this:
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)
Edit: An arange
doesn't make sense there, the cdf will always be the same for all points between x and x+1.
Is this what you're after? I have provided a function for approximating the cdf and plotted it. (Assuming you want to input a pdf array with y-values)
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()
精彩评论