サンプル平均値の動的シミュレーション
Matplotlibの利用
同じ母集団からのサンプルであっても、サンプルの具体的な値は、サンプルごとに異なりうる。このことを、シミュレーションで見てみる。
リスト1のスクリプトを実行すると、次のコード
n = int(input('n = '))
mu = float(input('mu = '))
sd = float(input('sd = '))
が実行されて、サンプルのデータの個数n、母集団の正規分布の平均mu、標準偏差sdが設定される。
次のコードにより、平均mu、標準偏差sdの正規分布からn個のデータがとられる。
x = rng.normal(loc=mu, scale=sd, size=n)
上のコードでサンプリングされたデータxが、次のコードで横軸上に青の丸で表示される。
plt.plot(x, [0]*n, 'o', c='b',
markerfacecolor='none')
サンプリングと表示の繰り返しを、次のコードでアニメーションとして実行している。
anim = animation.FuncAnimation(fig,
plot, interval=2000, cache_frame_data=False)
アニメーションは、図1のように表示される。

図1
サンプリングされた値が、青の丸で横軸上に並べられている。サンプルの平均値が緑の菱形で表示されている。アニメーションの画面ごとに、サンプルされたデータ値と平均値が表示され、横軸上を動いているので、サンプルによってデータ値がどのように変わるのかが動きとしてわかる。画面に表示されている橙色のグラフは、母集団の正規分布である。母集団の平均値の位置は、赤の縦線で示されている。サンプルの分布と母集団の関係を視覚的に見ることができる。
アニメーションの終了は、アニメーションの表示Windowの右上角のX印アイコンをクリックすればよい。
参考文献
岡本安晴「いまさら聞けないPythonでデータ分析――多変量解析,ベイズ統計分析(PyStan,PyMC)――」2019、丸善出版
岡本安晴「データを使いこなすための統計入門」2022、22世紀アート
付録
import numpy as np
import scipy.stats as ss
import matplotlib.pyplot as plt
import matplotlib.animation as
animation
n = int(input('n = '))
mu = float(input('mu = '))
sd = float(input('sd = '))
xcoord = np.linspace(mu-5*sd, mu+5*sd,
1000)
ycoord = ss.Normal(mu=mu,
sigma=sd).pdf(xcoord)
y_max = np.max(ycoord)
rng = np.random.default_rng()
fig = plt.figure(figsize=(12,5))
def plot(data):
x = rng.normal(loc=mu,
scale=sd, size=n)
mean = np.mean(x)
plt.clf()
plt.plot([mu - 5*sd, mu +
5*sd], [0, 0], lw=1, c='k')
plt.plot(xcoord, ycoord,
c='orange', label='Normal distribution')
plt.plot([mu,mu],
[-0.1*y_max, 1.1*y_max], c='r', label=f'$\mu$={mu}')
plt.plot(x, [0]*n, 'o',
c='b', markerfacecolor='none')
plt.plot([mean], [0],
color='g', marker='D',
markersize=15, label=fr'mean={mean:.3f}')
plt.xticks([mu - 5*sd, mu,
mu + 5*sd])
plt.title(fr'$\mu$={mu},
$\sigma$={sd}, n={n}',
fontsize=18)
plt.legend()
anim = animation.FuncAnimation(fig,
plot, interval=2000, cache_frame_data=False)
plt.show()