ヒストグラムを描く
Pythonのmatplotlibライブラリにおけるhist関数でヒストグラムを描画できます。
#インポート
import numpy as np
import scipy as spimport matplotlib.pyplot as plt
# データセットの読み込み
score = np.loadtxt('score.txt', skiprows=1)
X = score[:,0]#ヒストグラム描画
plt.hist(X, bins=5, range=(0,5))
plt.xlabel('score')#図の保存
plt.savefig('score_hist.png')
#プロット
plt.show()
histのbinsでビンの数を定義し、rangeでビンの幅を決定しています。
また、savefigで図を保存します。
ヒストグラムを確率密度にしたいときはnormed=Trueを追加します。
plt.hist(X, bins=5, range=(0,5),normed=True)
plt.xlabel('score')
plt.savefig('score_hist2.png')
plt.show()
なお、ヒストグラムの数値データはNumpyにも同様のhistgram関数があるのでそれを利用します。
print(np.histogram(X, bins=5, range=(0,5)))
array([ 0, 3, 3, 18, 16]), array([ 0., 1., 2., 3., 4., 5.])