Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【matplotlib】histogram関数でbin化したデータを使ってプロットしたい

import random
import numpy as np
import matplotlib.pyplot as plt

a = [random.random() for i in range(100)]

val1, base1 = np.histogram(a, bins=100, range=(0.4, 0.8))

みたいな感じでヒストグラムを作る
val1とbase1にはヒストグラムのあるビンのサンプル数とx軸のための値(等ビン幅のリスト)が入っている

len(base1), len(val1)
としてみると、101, 100と返ってくるのでこれをなんとか処理してからプロットする必要がある


この記事がわかりやすい

■ 過去記事 : Matplotlib - Stepped histogram with already binned data



記事がなくなるとわからなくなるのでメモっておく

def plot_binned_data(axes, binedges, data,
*args, **kwargs):
#The dataset values are the bin centres
x = (binedges[1:] + binedges[:-1]) / 2.0
#The weights are the y-values of the input binned data
weights = data
return axes.hist(x, bins=binedges, weights=weights,
*args, **kwargs)


import numpy
import matplotlib.pyplot as plt

#Create a dataset
dataset = numpy.random.normal(size=100)
#Bin the dataset
binedges = numpy.linspace(-5.0, 5.0, num=10)
y, binedges = numpy.histogram(dataset, binedges)

#Plot the dataset
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plot_binned_data(ax, binedges, y, histtype="step")
plt.show()

2つのヒストグラムを重ね合わせたいときは、plot_binned_data()関数を2回呼べばOK
あとは plot_binned_data() の引数にlabelとかを付けてもOK



とりあえずここをみる。

■ 参考 : [Python]Matplotlibでヒストグラムを描画する方法

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=[12, 12])

# もし複数枚プロットしたい時はここをいじる
# 2x2の場合は fig.add_subplot(2,2,1)として、最後の数字を1~4で変える(最初のプロットはi=0ではないことに注意)
ax = fig.add_subplot(1,1,1)

# ヒストグラムを取る時の範囲はrange指定する
# 0〜最大値*1.1とかにしておくのが吉
ax.hist(x, bins=50, range=[0, 10])
ax.set_title('hogehoge')
ax.set_xlabel('xlabel')
ax.set_ylabel('histogram')
#fig.show()
fig.savefig("hoge.png")

例えばsubplot(2, 2, 1)のように分割をした時に、プロット全体のタイトルをつけたい時は、

fig.suptitle("graphs")

のようにする
ただ、なぜかtitleとplotの間の隙間がかなり大きくなってしまったので、今回は使わなかった・・・・・

原因はドキュメントを見たらわかった

■ 参考 : subplots

fig.suptitle("graphs", y=0.90)

とy座標を手で調整すればOK
xもあるけど、そっちは0.5でいいだろう



ランキング参加中です

↓クリックしていただけると嬉しいです〜