静かなる名辞

pythonとプログラミングのこと


【python】matplotlibのhistで棒の上にラベルを表示

 plt.histはデータを与えるとそのままヒストグラムをプロットしてくれますが、棒との位置関係に基づいてテキストなどを表示させようとすると、ちょっと困ります。

 しかし、plt.histの返り値を利用して棒の頂点の座標を取得すれば、そのままプロットすることができます。

Returns:
n : array or list of arrays
The values of the histogram bins. See normed or density and weights for a description of the possible semantics. If input x is an array, then this is an array of length nbins. If input is a sequence of arrays [data1, data2,..], then this is a list of arrays with the values of the histograms for each of the arrays in the same order.

bins : array
The edges of the bins. Length nbins + 1 (nbins left edges and right edge of last bin). Always a single array even when multiple data sets are passed in.

patches : list or list of lists
Silent list of individual patches used to create the histogram or list of such list if multiple input datasets.

matplotlib.pyplot.hist — Matplotlib 3.0.2 documentation

 nとbinsがほしい情報です。patchesはとりあえず使いません。

 xy座標でいうと、nがy、binsがxです。ただしbinsは棒の両端の座標で、棒の数+1の要素数を持ちます。平均してやれば真ん中になります。

 以下は各棒の上に棒の高さ(データ数)をプロットするサンプルです。

import numpy as np
import matplotlib.pyplot as plt

n, bins, _ = plt.hist(np.random.uniform(size=1000))
xs = (bins[:-1] + bins[1:])/2
ys = n.astype(int)

for x, y in zip(xs, ys):
    plt.text(x, y, str(y), horizontalalignment="center")
plt.savefig("result.png")

result.png
result.png

 このように、座標さえ取得できれば任意のテキストや図形をプロットすることができます。