簡単な統計とグラフ描画
Pythonは汎用プログラミング言語であるので、用途は統計計算やグラフ描画に限られないが、プログラミングの手始めとしては統計計算とグラフ描画があげられると思う。
表1は、e-Statの「令和6年1月1日住民基本台帳人口・世帯数、令和5年(1月1日から同年12月31日まで)」から一部をコピー・編集したものである。
表1 令和6年1月1日住民基本台帳人口・世帯数より
都・県 |
人口(人) |
千葉県 |
6310158 |
東京都 |
13911902 |
神奈川県 |
9208688 |
表1の棒グラフを描くスクリプトをリスト1のように作成した。
リスト1
import numpy as np
import matplotlib.pyplot as plt
data = np.array([['chiba', 6310158],
['tokyo', 13911902],
['kana\ngawa', 9208688]])
# 文字列中の\nは復帰改行を表す
v_data = np.array(data.T[1],
dtype=int)
# 文字列データdata.T[1]を数値データに変換
plt.bar(data.T[0], v_data)
plt.xticks(fontsize=16)
plt.yticks(np.arange(0, 15000001,
5000000),[f'{v:,d}' for v in np.arange(0, 15000001, 5000000)] )
plt.tight_layout()
plt.show()
リスト1を実行すると図1のグラフが表示される。
図1
棒グラフを描く関数barは
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html
に説明されている。
表2に示すデータが与えられたとする。
表2(仮想データ)
56 , 39 , 53 , 38 , 67 37 , 23 , 55 , 67 , 39 38 , 51 , 50 , 44 , 61 53 , 46 , 68 , 67 , 55 |
これらの平均値などの統計量は、Pythonの関数
平均値を求める:numpy.mean
最小値を求める関数:numpy.min
最大値を求める関数:numpy.max
パーセンタイルを求める関数:numpy.percentile
標準偏差を求める関数:numpy.std
を用いて求めることができる。
表2のデータの統計量を求めるスクリプト例を、リスト2に示す。
リスト2
import numpy as np
data = [
56 ,
39 , 53 , 38 , 67 ,
37 ,
23 , 55 , 67 , 39 ,
38 ,
51 , 50 , 44 , 61 ,
53 ,
46 , 68 , 67 , 55
]
mean = np.mean(data)
print('mean =', mean)
x_min = np.min(data)
print('min =', x_min)
x_max = np.max(data)
print('max =', x_max)
q1, q2, q3 = np.percentile(data, [25,
50, 75])
print('Q1 =', q1, ' Q2 =', q2, ' Q3 =', q3)
sd = np.std(data)
print('standard deviation =', sd)
リスト2のスクリプトを実行すると、以下の出力を得る。
mean = 50.35
min = 23
max = 68
Q1 = 39.0 Q2 = 52.0 Q3 = 57.25
standard deviation =
12.030274311087009
上の分析結果を基に、ヒストグラムを描くスクリプトをリスト3のように用意した。
リスト3
import numpy as np
import matplotlib.pyplot as plt
data = [
56 ,
39 , 53 , 38 , 67 ,
37 ,
23 , 55 , 67 , 39 ,
38 ,
51 , 50 , 44 , 61 ,
53 ,
46 , 68 , 67 , 55
]
r = plt.hist(data,
bins=np.arange(20,71,10), color='aqua', edgecolor='b')
print(r)
plt.xticks(np.arange(20,71,10))
plt.ylabel('Frequency', fontsize=14)
plt.show()
ヒストグラムを描く関数の呼び出し
r = plt.hist(data,
bins=np.arange(20,71,10), color='aqua', edgecolor='b')
において引数bins=np.arange(20,71,10)の指定は、ヒストグラムにおける級の境界値を指定するものである。上の分析結果における最大値と最小値の値から級境界値を決めた。
関数plt.histの戻り値rをprint(r)で出力すると、次の出力を得る。
(array([1.,
5., 2., 7., 5.]), array([20., 30., 40., 50., 60., 70.]), <BarContainer
object of 5 artists>)
各級内の度数と、用いられた級境界値が出力されている。
リスト3の実行によって、下図(図2)のグラフが表示される。
図2
ヒストグラムの描画関数histの説明は
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html
にある。