IT编程 > 脚本编程 > Python

利用python绘制正态分布曲线

440人参与2021-01-04

使用python绘制正态分布曲线,借助matplotlib绘图工具;

#-*-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()

以上就是利用python绘制正态分布曲线的详细内容,更多关于python 正态分布的资料请关注移动技术网其它相关文章!

您对本文有任何疑问!!点此进行留言回复

推荐阅读

猜你喜欢

Python趣味入门教程之循环语句while

08-27

详解Python 3.10 中的新功能和变化

04-28

Python os库常用操作代码汇总

11-03

python爬虫自动创建文件夹的功能

08-10

荐 2019全国大学生数学建模竞赛题目 A题 高压油管的压力控制

07-16

Python学习-列表的转换和增加操作

10-24

Pycharm-community-2020.2.3 社区版安装教程图文详解

12-08

在Python中使用判断语句和循环的教程

06-28

热门评论