一维高斯分布函数的绘制

35 投票
5 回答
174829 浏览
提问于 2025-04-17 15:52

我该如何使用均值和标准差的参数值(μ, σ)分别为(−1, 1)、(0, 2)和(2, 3)来绘制一维高斯分布函数的图呢?

我刚开始学习编程,正在使用Python。

谢谢大家的帮助!

5 个回答

21

你可以阅读这个教程,了解如何在Python中使用统计分布的函数。https://docs.scipy.org/doc/scipy/tutorial/stats.html

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

#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)

x = np.arange(-10, 10, .1)

#plot the pdfs of these normal distributions 
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))
24

根据原始语法,正确的格式是这样的,并且已经进行了正确的规范化:

def gaussian(x, mu, sig):
    return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)
57

使用非常棒的 matplotlibnumpy 这两个工具包

from matplotlib import pyplot as mp
import numpy as np


def gaussian(x, mu, sig):
    return (
        1.0 / (np.sqrt(2.0 * np.pi) * sig) * np.exp(-np.power((x - mu) / sig, 2.0) / 2)
    )


x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
    mp.plot(x_values, gaussian(x_values, mu, sig))

mp.show()

会生成类似下面这样的图

用matplotlib生成的一维高斯分布图

撰写回答