二項分布のヒストグラムのPythonコード
二項分布 $B(n,p)$ のヒストグラムをPythonで出力してみよう。
二項分布の出力
試行回数n
と成功確率p
によって二項分布 $B(n,p)$ を定める.
scipy.stats
のbinom.pmf()
によって, 二項分布のそれぞれの確率を計算する.
matplotlib.pyplot
で棒グラフ.bar
を描くことでヒストグラムを作成する.
Pythonコード.
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binom
# 二項分布の情報
n = 100 # 試行回数
p = 0.3 # 成功確率
# 二項分布を表示
x_values = np.arange(0, n + 1)
binomial_probs = binom.pmf(x_values, n, p)
plt.bar(x_values, binomial_probs, color='y', alpha=0.7, label = "Binomial-distribution")
# グラフの表示
plt.legend() #凡例表示
plt.xlabel("Number of Successes")
plt.ylabel("Probability")
plt.title(f"Binomial Distribution (n={n}, p={p})")
plt.grid(True)
plt.show()
