Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@natsu-re

# 問題

もしかしたらナンセンスかもしれないけど、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
4
Help us understand the problem. What are the problem?