利用python繪製正態分佈曲線
阿新 • • 發佈:2021-01-06
使用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.2) y_2 = gd(x,1.0) y_3 = gd(x,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$',\sigma^2=5.0$','$\mu = -2,\sigma^2=0.5$']) plt.show()
以上就是利用python繪製正態分佈曲線的詳細內容,更多關於python 正態分佈的資料請關注我們其它相關文章!