ヒストグラムしたい(pandas.DataFrame.plot.hist
)
1data.plot(kind="hist", bins=ビン数, title="ヒストグラム")
2data.plot(kind="hist", bins=ビン数, stacked=True, title="積み上げヒストグラム")
3data.plot.hist(by=["カラム名"], bins=ビン数)
pandas.DataFrame.plot.histを使って数値データをヒストグラムにできます。
by
オプションにグループ化に使うカラム名を指定します。
bins
オプションでビン数を変更できます。デフォルトは10
になっています。
その他にpandas.DataFrame.histとmatplotlib.pyplot.histのオプションも利用できます。
注釈
カラム内のデータがstr型
の場合、このメソッドは使えません(たぶん)。
あらかじめデータフレームを集計して、棒グラフ(pandas.DataFrame.plot.bar
)を使う必要があります(たぶん)。
重要
ヒストグラムはいろんなことを教えてくれます。 実験で測定したデータは、まずヒストグラムにしてその分布を確認しましょう。
ビニングしたい(bins
)
1bins = [0, 10, 20, 30, 40, 50, 60, 70, 80]
2data.plot.hist(bins=bins)
bins
オプションを使ってビニングを変更できます。
デフォルトはbins=10
となっていて、均等に10分割されます。
リストを指定して、任意の間隔でビニングできます。
統計情報を自動計算したい
1def hbar(data, x, bins, xmin, xmax, **kwargs):
2
3 # x で指定したカラムのコピーを作成
4 copied = data[[x]].copy()
5
6 # Entries
7 entries = len(copied)
8
9 # Underflow
10 q = f"{x} < {xmin}"
11 uf = copied.query(q).count().iloc[0]
12
13 # Overflow
14 q = f"{x} > {xmax}"
15 of = copied.query(q).count().iloc[0]
16
17 # Valid
18 q = f"{xmin} <= {x} <= {xmax}"
19 v = copied.query(q)
20 n = len(v)
21 mean = v.mean().iloc[0]
22 rms = v.std().iloc[0]
23
24 stats = {
25 "entries": int(entries),
26 "underflow": int(uf),
27 "overflow": int(of),
28 "mean": mean,
29 "rms": rms
30 }
31 plot = v.plot.hist(bins=bins, **kwargs)
32 return plot, stats
ROOTのTH1クラス
を真似してヒストグラムを作ってみました。