Pythonでの正規分布のスケーリング

Sep 17 2020

正規分布のヒストグラムをプロットし、それに対応する正規分布もプロットしたいと思います。で正規化されたy軸の正規分布に関してオンラインで利用できるいくつかの例がありますdensity=True。私の例では、密度タイプの正規化なしで正規分布曲線を作成しようとしています。おそらく、これは暗黙のうちに数学的な問題である可能性がありますが、分布曲線を「非正規化」する方法を理解できませんでした。以下は私のコードです:

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

mu = 1e-3
std = 1.0e-4
nsize = 10000
ymax = 5000

# Generate some data for this demonstration.
data = norm.rvs(mu, std, size=nsize)

# Plot the histogram.
plt.hist(data, bins=20, color='b', edgecolor='black')

# Plot the PDF.
xmin, xmax = [0.5e-3, 1.5e-3] #plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)                      # something to do with this line
plt.plot(x, p, 'k', linewidth=2)
plt.axvline(mu, linestyle='dashed', color='black')
plt.ylim([0, ymax])

これにより、次のプロットが生成されます。

ご覧のとおり、ヒストグラムの下の面積nsizeは、データポイントの数である10000()に等しくなります。ただし、「分布曲線」ではそうではありません。ヒストグラムとの曲線の一致を取得するにはどうすればよいですか?

回答

4 QuangHoang Sep 17 2020 at 10:15

合計がにplt戻るようです。だから私たちはただスケーリングすることができます:histnsizep

# Plot the histogram.
hist, bins, _ = plt.hist(data, bins=20, color='b', edgecolor='black')

# Plot the PDF.
xmin, xmax = [0.5e-3, 1.5e-3] #plt.xlim()

# changes here
p = norm.pdf(bins, mu, std)           
plt.plot(bins, p/p.sum() * nsize , 'r', linewidth=2)

出力: