この記事では、Pythonモジュール「NumPy「」Matplotlib」で乱数をヒストグラム化する方法をソースコード付きで紹介します。
乱数のヒストグラム
NumPyで求めた乱数のヒストグラムを計算し、Matplotlibでグラフ化してみます。
ソースコード
サンプルプログラムのソースコードです。
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def main():
# サンプル数
N = 100
# 整数乱数配列を生成
x = np.random.rand(N)
y = x
# ヒストグラムの算出
hist, bins = np.histogram(y.ravel(),N,[0,1])
# ビンの末尾を削除して配列のサイズをhistと揃える
bins = np.delete(bins, -1)
# グラフ表示
plt.xlim(0, 1) # x軸の範囲
plt.ylim(-5, 30) # y軸の範囲
plt.scatter(bins, hist) # 散布図
plt.xlabel("Number", fontsize=20)
plt.ylabel("Value", fontsize=20)
plt.grid()
plt.show()
if __name__ == '__main__':
main()
実行結果
サンプルプログラムの実行結果です。

コメント