0
1

More than 1 year has passed since last update.

適切なヒストグラムの描き方

Posted at

別の記事で描かれているのはヒストグラムではなく plot.bar による棒グラフです。そこに示されているプログラムは必ず原点から描き始めるので,負の値を含むデータに対応しないとか,原点から大きく離れたデータ群の場合に左側に広大な空間ができるとかの欠点があります。

作者は bin の数を指定した場合に思うようjなヒストグラムにならないと思ったのでしょうが,以下のように bin を階級の区切り値ベクトルで定義すれば,思うような簡単にきれいなヒストグラムが書けます。

以下のプログラム例では,階級幅 classW を指定すれば,bins をベクトル指定するための min_x, max_x を計算します。min_x, max_x を別の計算式で求めるとか,plt.hist の他のパラメータの指定はお好きなように。

要するに,bin をベクトルで指定しましょうということです。例えば,ヒストグラムの特徴でもあるが,bin を不等間隔にすることもできます。

# 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

min_x = int(min(data) / classW) * classW
max_x = int(max(data) / classW + 2) * classW

from matplotlib import pyplot as plt
plt.hist(data, bins=range(min_x, max_x, classW))
# plt.xticks(x, rotation=90)
plt.show()

Figure_1.png

0
1
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
1