Skip to content

Instantly share code, notes, and snippets.

@mkacky
Last active August 29, 2015 14:03
Show Gist options
  • Save mkacky/e934d1cf910f76e98cb9 to your computer and use it in GitHub Desktop.
Save mkacky/e934d1cf910f76e98cb9 to your computer and use it in GitHub Desktop.
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
import numpy as np
import matplotlib.pyplot as plt
##input_data = np.loadtxt("normal.dat")
## 入力データ
## テキストの代わりに乱数を入力値に使用する
np.random.seed(2014)
## Java等とは異なり、Randomインスタンスを作成しない
## seedを与える
mu, sigma = 40, 20
## 平均値と標準偏差
input_data = np.random.normal(mu, sigma, 2000)
## 上記の平均値と標準偏差をパラメータにもつ正規分布に従うサンプルを2000個生成する
## これを入力値として使用する
width =10
## ビンの幅を設定
## width = int(sys.argv[1]) # 引数から設定
min_input, max_input = np.amin(input_data), np.amax(input_data)
## 入力データの最小値と最大値を求める
if max_input == 0:
num_interval = - int((min_input - width) / width)
elif min_input == 0:
num_interval = int((max_input + width) / width)
else:
num_interval = int((max_input + width) / width) - int((min_input - width) / width)
## ビンの数を求める
## 例:最大値37、最小値-23、ビン幅10ならば、 num_interval = 47/10 - (-33)/10 = 7である。
## 例:最大値-3, 最小値-26、ビン幅10ならば、num_interval = 3/10 - (-36)/10 = 3である。
## int((max_input + width) / width) は正のビンの数
## - int((min_input - width) / width) は負のビンの数
## 最大値か最小値のどちらかが0であるときにズレが発生するので回避
if min_input == 0:
min_range = 0
else:
min_range = int((min_input - width) / width)
bins_index = np.arange( min_range, min_range + num_interval + 1) * width
## ビンの境界点を表す数列
## pyplot.hist()関数の返り値indと同等のものを表す
## 7 intervals は 8 edgesが必要。
y, ind, patches = plt.hist(input_data, bins_index)
## ビンを指定した状態で、ヒストグラムを作成する
plt.savefig("histgram.png", bbox_inches="tight")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment