Help us understand the problem. What is going on with this article?

numpyでヒストグラムを作る

問題

最も簡単なやり方はmatplotlibを使うことです。例えば、[Python]Matplotlibでヒストグラムを描画する方法

もしかしたらナンセンスかもしれないけど、numpyのnp.histogramからやりたかったのでここにメモする。np.histogramから値を取ってくるには、

hist, bins = np.histgram(data)

のようにすればいいけれど、binsにはbinの両端の値が入っていて、だから

plt.bar(bins, hist)
plt.show()

とやっても、配列の長さが一致していないと怒られる。どうしたらいいのだろうか。

方法

binsの値の代わりにbinの中央値の値を吐き出す関数を書けば良い。以下のコードを書いた。

import matplotlib.pyplot as plt
import numpy as np

def hist(arr, nbins=10, weights=None, isNormed=False):
    """
    Args:
        arr: 1d array
        bins: the number of bins
    Returns:
        hist: 1d array, histogram
        bins[:-1]: 1d array, centers of bins
    """
    hist, bins = np.histogram(arr, bins=nbins, weights=weights)
    if isNormed: hist = hist/hist.sum()
    halfDeltaBin = np.diff(bins)[0]/2
    bins = bins + halfDeltaBin
    return hist, bins[:-1]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away