ヒストグラムのプロット

平均 50, 標準偏差 250 の正規分布に従う乱数を10000個生成し、
そのヒストグラムを作成する。



#!/usr/bin/env python


import random
import matplotlib.pyplot as plt


def plot():
    mu = 50
    sigma = 250
    MAX = 1000
    MIN = -1000
    N = 10000

    data = [random.normalvariate(mu,sigma) for i in range(N)]

    fig = plt.figure()

    ax = fig.add_subplot(1,1,1)
    ax.hist(data, bins=100, range=(MIN,MAX))
    ax.set_ylabel("frequency")
    ax.grid()
    
    plt.savefig("test.png")

    plt.close()


if __name__=="__main__":
    plot()

hist()の仕様(一部):
hist(x, bins=100, range=(-1000,1000), normed=False, cumulative=False, histtype="bar")

  • x: ヒストグラムにする対象のデータ
  • bins: 縦棒の本数(デフォルトは10)
  • range: 表示する横軸の幅(デフォルトは(xの最小値,xの最大値))
  • normed: 度数をデータ数で正規化するかどうか(デフォルトはFalse)
  • cumulative: 累積ヒストグラムとして表示するか(デフォルトはFalse)
  • histtype: ヒストグラムのタイプ。"bar" の他, "step", "stepfilled"等がある (デフォルトは"bar")

hist()の返り値: (pdf, bins, patches)

  • pdf: 各縦棒の度数が、リストで格納される
  • bins: 各縦棒の値が、リストで格納される
  • patches: 各縦棒の座標値が格納される。

      (histtype="bar"ならmatplotlib.patches.Rectangle、histtype="step"なら、matplotlib.patches.Polygon)

※より詳しくは、http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.hist を参照