LoginSignup
0
0

More than 1 year has passed since last update.

ヒストグラムを作る(python)

Last updated at Posted at 2022-01-01

ヒストグラムをつくるプログラム

タイトルのままです。matplotlib標準のヒストグラム(参考:[Python]Matplotlibでヒストグラムを描画する方法 )が妙に使いにくいと感じたため、作りました。

入力はリスト型のデータ系列(当たり前だがfloat型かint型)と階級幅、出力がヒストグラムの縦軸(各度数)と横軸(各階級幅の上限)。
以下、ソースコード。
データはアジア各国の平均寿命(総務統計局「世界の統計2020」より)。参考サイトは、http://www.stat.go.jp/naruhodo/4_graph/shokyu/histogram.html まで。

makeHistgram.py
def makeHistgram(data:list, classW:float)->list:
    maxValue = max(data)
    histgram = [0] * (int(maxValue / classW)+1)
    for h in data:
        h_class = int(h / classW)
        histgram[h_class] += 1
    x = [(e)*classW for e in range(len(histgram))]
    y = histgram
    return x, y

# data
data = [84, 63, 77, 65, 82, 70, 76, 69, 69, 72, 77, 71, 83, 69, 72, 75, 75, 64, 83, 75, 76, 76, 76, 70, 67, 73, 69, 76, 76, 75, 67]
# class width
classW = 5

# make histgram
x,y = makeHistgram(data, classW)
print(x,y)

# make graph
from matplotlib import pyplot as plt
plt.bar(x,y,classW-1)
plt.xticks(x, rotation=90)
plt.show()

出力結果は

result
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 7, 6, 12, 4]

Figure_1.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0