Matplotlib hist() 関数
hist()ヒストグラムを描画するために使用され、データを複数の区間(bins)に分割し、各区間内のデータの出現頻度を集計します。
ヒストグラムは、データ分布(中心傾向、ばらつき、歪度など)を調査するための基本的なツールです。
関数定義
pyplot インターフェース
matplotlib.pyplot.hist(x, bins=None, range=None, density=False,
weights=None, cumulative=False, bottom=None, histtype='bar',
align='mid', orientation='vertical', rwidth=None, log=False,
color=None, label=None, stacked=False, **kwargs)
Axes インターフェース
Axes.hist(x, bins=None, range=None, density=False, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, color=None,
label=None, stacked=False, **kwargs)
パラメータの説明
| パラメータ | 型 | 説明 |
|---|---|---|
| x | array または array のシーケンス | 入力データ。複数のデータセットを渡すことができます |
| bins | int または sequence | 区間数または区間境界のシーケンス。デフォルトでは 'auto' メソッドで自動選択されます |
| range | tuple | データ範囲 (lower, upper)。範囲外のデータは無視されます |
| density | bool | True の場合、確率密度ヒストグラム(面積の合計が 1)を描画し、頻度ではありません |
| weights | array-like | 各データ点の重み |
| cumulative | bool または -1 | True の場合、累積ヒストグラムを描画します。-1 は大きい方から小さい方への累積を意味します |
| histtype | str | ヒストグラムの種類:'bar'(デフォルト)、'barstacked'(積み上げ)、'step'(階段線)、'stepfilled'(塗りつぶし階段) |
| align | str | バーの配置:'mid'(中央、デフォルト)、'left'(左揃え)、'right'(右揃え) |
| orientation | str | 'vertical'(垂直、デフォルト)または 'horizontal'(水平) |
| rwidth | float | バーの相対的な幅。1.0 は隙間なしを意味します |
| log | bool | True の場合、y 軸は対数スケールを使用します |
| color | color または list | バーの色 |
| label | str または list | 凡例ラベル |
| stacked | bool | 複数のデータセットの場合に積み上げ表示するかどうか |
hist() の戻り値は3つの要素を持つタプルです:
(n, bins, patches)。n は各区間の頻度/密度、bins は区間境界、patches は描画されたバーのオブジェクトです。
使用例
例1:基本的なヒストグラム
実例
import matplotlib.pyplot as plt
import numpy as np
# 正規分布のランダムデータを生成
np.random.seed(42)
data = np.random.randn(1000)
fig, ax = plt.subplots(layout='constrained')
# ヒストグラムを描画
n, bins, patches = ax.hist(data, bins=30,
color='steelblue', edgecolor='white')
# 最大値が含まれる区間をハイライト
max_idx = np.argmax(n)
patches[max_idx].set_facecolor('#e74c3c')
ax.set_title('Histogram of Normal Distribution')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.axvline(x=0, color='red', linestyle='--', alpha=0.7)
ax.grid(axis='y', alpha=0.3)
plt.show()
import numpy as np
# 正規分布のランダムデータを生成
np.random.seed(42)
data = np.random.randn(1000)
fig, ax = plt.subplots(layout='constrained')
# ヒストグラムを描画
n, bins, patches = ax.hist(data, bins=30,
color='steelblue', edgecolor='white')
# 最大値が含まれる区間をハイライト
max_idx = np.argmax(n)
patches[max_idx].set_facecolor('#e74c3c')
ax.set_title('Histogram of Normal Distribution')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.axvline(x=0, color='red', linestyle='--', alpha=0.7)
ax.grid(axis='y', alpha=0.3)
plt.show()
例2:複数データセットの比較ヒストグラム
実例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
# 3つの異なる分布のデータ
data1 = np.random.normal(0, 1, 1000) # 標準正規
data2 = np.random.normal(2, 1.5, 800) # 平均=2, 標準偏差=1.5
data3 = np.random.normal(-1, 0.5, 600) # 平均=-1, 標準偏差=0.5
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
# 複数データの比較には透明度と異なる色を使用
ax.hist(data1, bins=30, alpha=0.6, color='steelblue',
label='N(0, 1)', edgecolor='white')
ax.hist(data2, bins=30, alpha=0.6, color='coral',
label='N(2, 1.5)', edgecolor='white')
ax.hist(data3, bins=30, alpha=0.6, color='mediumseagreen',
label='N(-1, 0.5)', edgecolor='white')
ax.set_title('Comparing Multiple Distributions')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
import numpy as np
np.random.seed(42)
# 3つの異なる分布のデータ
data1 = np.random.normal(0, 1, 1000) # 標準正規
data2 = np.random.normal(2, 1.5, 800) # 平均=2, 標準偏差=1.5
data3 = np.random.normal(-1, 0.5, 600) # 平均=-1, 標準偏差=0.5
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
# 複数データの比較には透明度と異なる色を使用
ax.hist(data1, bins=30, alpha=0.6, color='steelblue',
label='N(0, 1)', edgecolor='white')
ax.hist(data2, bins=30, alpha=0.6, color='coral',
label='N(2, 1.5)', edgecolor='white')
ax.hist(data3, bins=30, alpha=0.6, color='mediumseagreen',
label='N(-1, 0.5)', edgecolor='white')
ax.set_title('Comparing Multiple Distributions')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
例3:密度ヒストグラム + フィッティング曲線
実例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
data = np.random.randn(1000)
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
# density=True で確率密度を描画(頻度ではなく)
ax.hist(data, bins=30, density=True, alpha=0.7,
color='steelblue', edgecolor='white', label='Data Histogram')
# 理論上の正規分布曲線を重ねる
from scipy import stats
x = np.linspace(-4, 4, 200)
pdf = stats.norm.pdf(x, loc=0, scale=1)
ax.plot(x, pdf, 'r-', linewidth=2, label='Theoretical N(0,1) PDF')
ax.set_title('Density Histogram with PDF Curve')
ax.set_xlabel('Value')
ax.set_ylabel('Probability Density')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
import numpy as np
np.random.seed(42)
data = np.random.randn(1000)
fig, ax = plt.subplots(figsize=(8, 5), layout='constrained')
# density=True で確率密度を描画(頻度ではなく)
ax.hist(data, bins=30, density=True, alpha=0.7,
color='steelblue', edgecolor='white', label='Data Histogram')
# 理論上の正規分布曲線を重ねる
from scipy import stats
x = np.linspace(-4, 4, 200)
pdf = stats.norm.pdf(x, loc=0, scale=1)
ax.plot(x, pdf, 'r-', linewidth=2, label='Theoretical N(0,1) PDF')
ax.set_title('Density Histogram with PDF Curve')
ax.set_xlabel('Value')
ax.set_ylabel('Probability Density')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
例4:累積ヒストグラム
実例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
data = np.random.randn(500)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# 左図:通常のヒストグラム
ax1.hist(data, bins=30, color='steelblue', edgecolor='white')
ax1.set_title('Standard Histogram')
ax1.set_xlabel('Value')
ax1.set_ylabel('Frequency')
# 右図:累積ヒストグラム
ax2.hist(data, bins=30, cumulative=True, color='coral',
edgecolor='white')
ax2.set_title('Cumulative Histogram')
ax2.set_xlabel('Value')
ax2.set_ylabel('Cumulative Frequency')
plt.show()
import numpy as np
np.random.seed(42)
data = np.random.randn(500)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
layout='constrained')
# 左図:通常のヒストグラム
ax1.hist(data, bins=30, color='steelblue', edgecolor='white')
ax1.set_title('Standard Histogram')
ax1.set_xlabel('Value')
ax1.set_ylabel('Frequency')
# 右図:累積ヒストグラム
ax2.hist(data, bins=30, cumulative=True, color='coral',
edgecolor='white')
ax2.set_title('Cumulative Histogram')
ax2.set_xlabel('Value')
ax2.set_ylabel('Cumulative Frequency')
plt.show()
例5:階段ヒストグラム (step histogram)
実例
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
data = np.random.exponential(scale=2, size=500)
fig, ax = plt.subplots(layout='constrained')
# histtype='stepfilled' で塗りつぶし階段ヒストグラムを描画
ax.hist(data, bins=30, histtype='stepfilled',
color='#3498db', alpha=0.6, edgecolor='black',
linewidth=1, label='Stepfilled')
# 階段線を重ねる
ax.hist(data, bins=30, histtype='step',
color='black', linewidth=2, label='Step outline')
ax.set_title('Step Histogram (histtype)')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
print("サンプル: step histogram displayed")
import numpy as np
np.random.seed(42)
data = np.random.exponential(scale=2, size=500)
fig, ax = plt.subplots(layout='constrained')
# histtype='stepfilled' で塗りつぶし階段ヒストグラムを描画
ax.hist(data, bins=30, histtype='stepfilled',
color='#3498db', alpha=0.6, edgecolor='black',
linewidth=1, label='Stepfilled')
# 階段線を重ねる
ax.hist(data, bins=30, histtype='step',
color='black', linewidth=2, label='Step outline')
ax.set_title('Step Histogram (histtype)')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
print("サンプル: step histogram displayed")
よくある質問
bins パラメータはどう選ぶ?
少なすぎるとデータの特徴を失い、多すぎるとノイズが入ります。
経験則:sqrt(n)(平方根則)、log2(n)+1(Sturges 則)、またはデフォルトの 'auto' を直接使用して自動選択します。
density=True とはどういう意味ですか?
頻度(count)を返すのではなく、ヒストグラムの総面積が 1 になるようにして、確率密度の推定値を生成します。確率密度関数(PDF)との比較に適しています。
その他の拡張