您的位置:宽带测速网 > 编程知识 > Matplotlib中如何绘制并分析概率分布函数和累积分布函数

Matplotlib中如何绘制并分析概率分布函数和累积分布函数

2025-06-27 17:07来源:互联网 [ ]

要绘制概率分布函数和累积分布函数,可以使用Matplotlib库中的hist函数和plot函数。

首先,需要导入Matplotlib库:

import matplotlib.pyplot as plt

接下来,可以创建一个随机变量的样本数据,并使用hist函数绘制概率分布函数:

import numpy as npdata = np.random.normal(loc=0, scale=1, size=1000)plt.hist(data, bins=30, density=True, alpha=0.6, color='b')plt.xlabel('Value')plt.ylabel('Probability')plt.title('Probability Distribution Function')plt.show()

这段代码将创建一个包含1000个从均值为0、标准差为1的正态分布中抽取的随机样本数据。然后,使用hist函数将数据绘制成直方图,其中参数density=True表示将直方图中的频数转换为概率。

接着,可以使用cumsum函数计算累积分布函数,并使用plot函数绘制:

counts, bin_edges = np.histogram(data, bins=30, density=True)cdf = np.cumsum(counts)plt.plot(bin_edges[1:], cdf, color='r')plt.xlabel('Value')plt.ylabel('Cumulative Probability')plt.title('Cumulative Distribution Function')plt.show()

这段代码将计算直方图的累积和,并使用plot函数绘制成累积分布函数。在上面的例子中,我们使用了正态分布的样本数据,你可以根据需要替换成其他概率分布的数据。