且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取文件并用Python绘制CDF

更新时间:2022-11-19 11:37:51

您有两个选择:

1:您可以先对数据进行装箱.使用numpy.histogram函数可以轻松完成此操作:

1: you can bin the data first. This can be done easily with the numpy.histogram function:


import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('Filename.txt')

# Choose how many bins you want here
num_bins = 20

# Use the histogram function to bin the data
counts, bin_edges = np.histogram(data, bins=num_bins, normed=True)

# Now find the cdf
cdf = np.cumsum(counts)

# And finally plot the cdf
plt.plot(bin_edges[1:], cdf)

plt.show()

2:而不是使用numpy.cumsum,只需针对小于该数组中每个元素的项目数绘制sorted_data数组即可(请参阅此答案以获取更多详细信息https://***.com/a/11692365/588071 ):

2: rather than use numpy.cumsum, just plot the sorted_data array against the number of items smaller than each element in the array (see this answer for more details https://***.com/a/11692365/588071):


import numpy as np

import matplotlib.pyplot as plt

data = np.loadtxt('Filename.txt')

sorted_data = np.sort(data)

yvals=np.arange(len(sorted_data))/float(len(sorted_data)-1)

plt.plot(sorted_data,yvals)

plt.show()