Lesson 07: 1D plots with random function which follow the normal distribution
依據常態分佈產生隨機亂數並作圖
Example Code
- import numpy as np;
- import matplotlib.pyplot as plt
- Distri1 = np.random.randn(2,20000);
- sigma2 = 1.0;
- sigma3 = 0.5;
- sigma4 = 0.2;
- mu =1.0;
- Distri2 = sigma2 * np.random.randn(20000) + mu;
- Distri3 = sigma3 * np.random.randn(20000) + mu;
- Distri4 = sigma4 * np.random.randn(20000) + mu;
- plt.figure(1);
- plt.subplot(211);
- plt.title(r'Random Numbers with Normal Distribution');
- plt.ylabel('distribution');
- plt.hist(Distri1[0], bins=20, histtype='bar', normed=True);
- plt.legend(["distribution"]);
- plt.subplot(212);
- plt.hist(Distri2, bins=20, histtype='step',color='red', normed=True);
- plt.hist(Distri3, bins=20, histtype='step',color='blue', normed=True);
- plt.hist(Distri4, bins=20, histtype='step',color='black', normed=True);
- plt.legend( ["$\mu=1, \sigma=1$","$\mu=1, \sigma=0.5$", "$\mu=1, \sigma=0.2$"]);
- plt.xlabel('value');
- plt.ylabel('distribution');
- plt.show();
Note and Comments
- import matplotlib.pyplot as plt 匯入圖形函式庫Matplotlib中的pyplot資料庫, 並命名爲plt 產生m個0到1的隨機數
- np.random.randn(n,m); 依常態分佈生成n組亂數, 每組亂數有m個資料點
- sigma * np.random.randn(m) + mu; 依常態分佈生成m個亂數資料, 其中標準差是sigma, mu是資料平均值,也就是N(mu,sigma)
- plt.figure(1) 宣告一個圖像的視窗
- plt.subplot(lmn) 圖像視窗有l行*m列個圖, 我們目前使用第一個圖
- plt.title(r'Distribution of Random [0,1]') 第一個圖的名稱爲 Distribution of Random [0,1]
- plt.ylabel('count') 設定y軸的名稱, plt.xlabel('count') 設定x軸的名稱
- plt.hist(Distri1[0], bins=10, histtype='bar', normed=False) 繪一維長條圖, 資料點爲Distri1[0]序列
- histtype='xxxx' 設定長條圖的格式: bar與stepfilled爲不同形式的長條圖, step以橫線標示數值.
- bin(n) 資料有n個binning(x軸切成n等分累積畫圖),
- normed=False, 資料在作圖時不作歸一化.
- plt.legend(["xxx"]); 設定圖例
- plt.show() 圖形設定完畢,開始作圖
result