matplotlib:绘制CDF的方法

时间:2013-05-29 14:40:29

标签: python matplotlib cdf

pythonmatplotlib,我必须在同一张图上绘制 2张CDF曲线:一张用于数据A,一张用于数据B.

如果我自己决定“ binning ”,我会执行以下操作并根据数据A获取100个直方图。(在我的情况下,A总是最多50%的大小B)

import numpy as np
import matplotlib

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.grid(True)

a = 0
nhist = 100                
b = np.max(samplesFromA)
c = b-a
d = float(c) / float(nhist)  #size of each bin
# tmp will contain a list of bins:  [a, a+d, a+2*d, a+3*d, ... b]
tmp = [a]
for i in range(nhist):
    if i == a:
    continue
    else:
    tmp.append(tmp[i-1] + d)

#  CDF of A 
ax.hist(samplesFromA, bins=tmp, cumulative=True, normed=True,
        color='red', histtype='step', linewidth=2.0,
        label='samples A')

# CDF of B
plt.hist(samplesFromB, bins=tmp, cumulative=True, normed=True,
        color='blue', alpha=0.5, histtype='step', linewidth=1.0,
        label='samples B')

结果如下(我裁剪了所有不相关的信息): enter image description here

最近我发现了sm.distributions.ECDF,我想与之前的实现进行比较。基本上,我将在我的数据上调用以下函数(并在其他地方决定最右边的bin的范围),而不计算任何bin

def drawCDF(ax, aSample):
    ecdf = sm.distributions.ECDF(aSample)
    x = np.linspace(min(aSample), max(aSample))
    y = ecdf(x)
    ax.step(x, y)
    return ax

以下是结果,使用相同的数据(同样,我手动裁剪出不相关的文字): enter image description here

事实证明,最后一个例子将太多的箱子合并在一起,结果不是一个非常精细的CDF曲线。幕后究竟发生了什么?

样品A(红色)包含 70个样品,而样品B(蓝色)包含 15 000

1 个答案:

答案 0 :(得分:1)

我建议你阅读source

如果你想要均匀分布的箱子:

x = np.linspace(min(aSample), 
                max(aSample),
                int((max(aSample) - min(aSample)) / step))

np.arange doc