如何在Python的matplotlib中绘制cdf?

2024-09-28 20:48:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为d的无序列表,看起来像:

[0.0000, 123.9877,0.0000,9870.9876, ...]

我只想使用Python中的Matplotlib基于这个列表绘制一个cdf图。但不知道我能不能用

d = []
d_sorted = []
for line in fd.readlines():
    (addr, videoid, userag, usertp, timeinterval) = line.split()
    d.append(float(timeinterval))

d_sorted = sorted(d)

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)

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

现在我正在使用此代码,但错误消息是:

Traceback (most recent call last):
File "hitratioparea_0117.py", line 43, in <module>
cdf = discrete_cdf(d_sorted)
TypeError: __init__() takes exactly 1 argument (2 given)

Tags: inself列表fordatalendefline
3条回答

我知道我去晚会迟到了。但是,如果您只想让cdf用于绘图而不用于将来的计算,则有一种更简单的方法:

plt.hist(put_data_here, normed=True, cumulative=True, label='CDF',
         histtype='step', alpha=0.8, color='k')

例如,生成one of these graphs的相关代码是:

plt.hist(dataset, bins=bins, normed=True, cumulative=True, label='CDF DATA', 
         histtype='step', alpha=0.55, color='purple')
# bins and (lognormal / normal) datasets are pre-defined

从matplotlib文档中编辑:This example可能更有帮助。

计算累积和cumsum的numpy函数在这里很有用

In [1]: from numpy import cumsum
In [2]: cumsum([.2, .2, .2, .2, .2])
Out[2]: array([ 0.2,  0.4,  0.6,  0.8,  1. ])

如前所述,来自numpycumsum工作良好。确保您的数据是正确的PDF(即总和为1),否则CDF不会以unityas it should结尾。下面是一个最小的工作示例:

import numpy as np
from pylab import *

# Create some test data
dx = 0.01
X  = np.arange(-2, 2, dx)
Y  = exp(-X ** 2)

# Normalize the data to a proper PDF
Y /= (dx * Y).sum()

# Compute the CDF
CY = np.cumsum(Y * dx)

# Plot both
plot(X, Y)
plot(X, CY, 'r--')

show()

enter image description here

相关问题 更多 >