Python绘制正态分布曲线

  使用Python绘制正态分布曲线,借助matplotlib绘图工具;
\[ f(x) = \dfrac{1}{\sqrt{2\pi}\sigma}\exp(-\dfrac{(x-\mu)^2}{2\sigma^2}) \]

1.png

#-*-coding:utf-8-*-
"""
python绘制标准正态分布曲线
"""
# ==============================================================
import numpy as np
import math
import matplotlib.pyplot as plt


def gd(x, mu=0, sigma=1):
    """根据公式,由自变量x计算因变量的值

    Argument:
        x: array
            输入数据(自变量)
        mu: float
            均值
        sigma: float
            方差
    """
    left = 1 / (np.sqrt(2 * math.pi) * np.sqrt(sigma))
    right = np.exp(-(x - mu)**2 / (2 * sigma))
    return left * right


if __name__ == '__main__':
    #  自变量
    x = np.arange(-4, 5, 0.1)
    #  因变量(不同均值或方差)
    y_1 = gd(x, 0, 0.2)
    y_2 = gd(x, 0, 1.0)
    y_3 = gd(x, 0, 5.0)
    y_4 = gd(x, -2, 0.5)

    #  绘图
    plt.plot(x, y_1, color='green')
    plt.plot(x, y_2, color='blue')
    plt.plot(x, y_3, color='yellow')
    plt.plot(x, y_4, color='red')
    #  设置坐标系
    plt.xlim(-5.0, 5.0)
    plt.ylim(-0.2, 1)

    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data', 0))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data', 0))

    plt.legend(labels=['$\mu = 0, \sigma^2=0.2$', '$\mu = 0, \sigma^2=1.0$', '$\mu = 0, \sigma^2=5.0$', '$\mu = -2, \sigma^2=0.5$'])
    plt.show()

转载于:https://www.cnblogs.com/chenzhen0530/p/10690653.html

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值