SciPy 中的概率密度函数表现与预期不同

Probability density function in SciPy behaves differently than expected

我正在尝试使用 Python 绘制正态分布曲线。首先我使用正态概率密度函数手动完成,然后我发现stats模块下的scipy中有一个exiting函数pdf。然而,我得到的结果却大不相同。

下面是我试过的例子:

import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats

mean = 5
std_dev = 2
num_dist = 50

# Draw random samples from a normal (Gaussion) distribution
normalDist_dataset = np.random.normal(mean, std_dev, num_dist)

# Sort these values.
normalDist_dataset = sorted(normalDist_dataset)

# Create the bins and histogram
plt.figure(figsize=(15,7))
count, bins, ignored = plt.hist(normalDist_dataset, num_dist, density=True)

new_mean = np.mean(normalDist_dataset)
new_std = np.std(normalDist_dataset)

normal_curve1 = stats.norm.pdf(normalDist_dataset, new_mean, new_std)
normal_curve2 = (1/(new_std *np.sqrt(2*np.pi))) * (np.exp(-(bins - new_mean)**2 / (2 * new_std**2)))

plt.plot(normalDist_dataset, normal_curve1, linewidth=4, linestyle='dashed')
plt.plot(bins, normal_curve2, linewidth=4, color='y')

结果表明我得到的两条曲线彼此有很大不同。

我的猜测是它与 binspdf 的行为与通常的公式不同有关。我对这两个图使用了相同的和新的均值和标准差。那么,如何更改我的代码以匹配 stats.norm.pdf 正在做的事情?

我还不知道哪条曲线是正确的。

函数plot简单地将点与线段连接起来。您的箱子没有足够的点来显示平滑的曲线。可能的解决方案:

....
normal_curve1 = stats.norm.pdf(normalDist_dataset, new_mean, new_std)
bins = normalDist_dataset # Add this line
normal_curve2 = (1/(new_std *np.sqrt(2*np.pi))) * (np.exp(-(bins - new_mean)**2 / (2 * new_std**2)))
....