Pythonでいい感じにヒストグラムを自動生成してくれる機能

結論からいうと、pythonの主要ライブラリ(numpy + matplotlib)ではまだ実現できない.

Histogram with Optimal Binwidth

numpy.histogram という機能がnumpyには存在する これとfrom matplotlib import pyplotなどを利用すると pythonで簡単にヒストグラムグラフを書くことができる. 具体的には pyplot.histという関数を使うのだが、この関数のデフォルトのbinの数が10に固定されており 放り込むデータ数に関係なくbin数10でプロットしようとしてくる. R言語ではbin数をいい感じに最適化してくれる機能があるそうだ *1. ヒストグラムってデータ解析の第一歩なので、なるべく手軽にやりたい。 そこでpythonにもR言語のようなoptimal なbin数を出す機能を追加しようという提案がなされた.

ENH: Automatic number of bins for np.histogram by nayyarv · Pull Request #6029 · numpy/numpy · GitHub

optimalなbin数をはじき出すためにはそれなりに複雑な計算を要するため、 追加するのはmatplotlibにではなくnumpyコミュニティの方で行うようだ。

ということで、この機能が追加されるまではpython + numpy + matplotlibではまだ、bin幅を自動最適化することはできないみたいだ

Edit :

New in version 1.11.0. If bins is a string from the list below, histogram will use the method chosen to calculate the optimal bin width and consequently the number of bins (see Notes for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the ‘auto’ option is suggested. Weighted data is not supported for automated bin size selection.

Ref: http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html#numpy-histogram

mcbiophys.hatenablog.com

mcbiophys.hatenablog.com

*1:hist() 関数では、自動的に階級数を決める方法として、 スタージェス/nclass.Sturges,フリードマン-ディアコニス/nclass.scott ,スコット/nclass.FD などの流儀が存在するらしい.このリンク先が参考に成る→ヒストグラム作成の裏側: R 関数探訪 hist() 編 - ほくそ笑む