python - 在 Python 中缩放正态分布

标签 python matplotlib normal-distribution

我想为正态分布绘制直方图,并在其上绘制相应的正态分布。网上有几个关于正态分布的例子,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])
这将产生以下图。 enter image description here
可以看出,直方图下方的面积将等于 10000 ( nsize ),这是数据点的数量。然而,“分布曲线”并非如此。如何获得与直方图匹配的曲线?

最佳答案

它看起来像 plt返回 hist总计为 nsize .所以我们可以缩放 p :

# 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)
输出:
enter image description here

关于python - 在 Python 中缩放正态分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930648/

相关文章:

python - 索引超出范围 - Python 中的快速排序

python - Matplotlib 艺术家在放大时保持相同大小但也随着平移移动?

python - matplotlib 散点图 x 轴标签

r - 为什么正常样本的直方图在模式附近比在尾部附近更粗糙?

r - 定义一个计算相关矩阵的协方差矩阵的函数

c++ - 创建具有均值和标准差的高斯随机发生器

python - 无法解析 'center' 。索引为 0 的序列项类型错误

python - 删除 numpy 数组中第一次出现的元素

python - 在干图中隐藏基线

python - python 将字符串拆分为正数和负数?