NumPy:ヒストグラムを作成する(histogram)

ヒストグラムは、データの分布を視覚化するための図です。NumPy の histogram 関数を使うと、データをビン(区間)に分けて、各ビンに含まれる要素数を数えることができます。

histogram の基本

np.histogram() は、ヒストグラムのデータ(度数とビンの境界)を返します。

import numpy as np

data = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5])

hist, bin_edges = np.histogram(data)
print(hist)       # [1 1 1 2 1 1 1 0 0 1]
print(bin_edges)  # [1.  1.4 1.8 2.2 2.6 3.  3.4 3.8 4.2 4.6 5. ]

hist が各ビンの度数(要素数)、bin_edges がビンの境界値です。デフォルトでは 10 個のビンに分けられます。

ビン数の指定

bins 引数でビンの数を指定できます。

data = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5])

# 5つのビンに分ける
hist, bin_edges = np.histogram(data, bins=5)
print(hist)       # [1 2 3 2 1]
print(bin_edges)  # [1.  1.8 2.6 3.4 4.2 5. ]

各ビンの範囲は [1.0, 1.8), [1.8, 2.6), … のように、左端を含み右端を含まない区間になります(最後のビンのみ右端も含む)。

ビンの境界を直接指定

リストで境界値を渡すと、ビンの範囲を細かく指定できます。

data = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5])

# 1〜2, 2〜3, 3〜4, 4〜5 の4つのビン
hist, bin_edges = np.histogram(data, bins=[1, 2, 3, 4, 5, 6])
print(hist)       # [1 2 3 2 1]
print(bin_edges)  # [1 2 3 4 5 6]

範囲の指定

range 引数でデータの範囲を指定できます。範囲外のデータは無視されます。

data = np.array([1, 2, 3, 4, 5, 100])

# 1〜10の範囲でヒストグラムを作成(100は除外)
hist, bin_edges = np.histogram(data, bins=5, range=(1, 10))
print(hist)  # [3 2 0 0 0]

正規化(密度)

density=True を指定すると、ヒストグラムが正規化されます。すべてのビンの面積の合計が 1 になります。

data = np.random.randn(1000)  # 正規分布のデータ

hist, bin_edges = np.histogram(data, bins=20, density=True)
print(hist.sum() * (bin_edges[1] - bin_edges[0]))  # ≒ 1.0

確率密度関数の近似として使いたいときに便利です。

matplotlib でヒストグラムを描画

NumPy の histogram はデータを計算するだけなので、グラフを描くには matplotlib を使います。

import matplotlib.pyplot as plt

data = np.random.randn(1000)

# NumPyで計算してmatplotlibで描画
hist, bin_edges = np.histogram(data, bins=30)
plt.bar(bin_edges[:-1], hist, width=np.diff(bin_edges), edgecolor='black')
plt.show()

ただし、matplotlib には plt.hist() という便利な関数があり、こちらを使うほうが簡単です。

data = np.random.randn(1000)

plt.hist(data, bins=30, edgecolor='black')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()

2次元ヒストグラム

np.histogram2d() を使うと、2変数のヒストグラムを作成できます。

x = np.random.randn(1000)
y = np.random.randn(1000)

hist, x_edges, y_edges = np.histogram2d(x, y, bins=20)
print(hist.shape)  # (20, 20)

ヒートマップとして可視化することで、2変数の分布の関係がわかります。

NumPy の histogram は分析の基礎となる機能です。データの分布を把握するときに活用してみてください。