Python で解析 12

“Advent Calendar 2013 - Python で解析!” の十二日目。matplotlib - 2

1. いつものごとく準備から

データ操作が続いたところで、久しぶりにチャートを。その前に、データの用意を…。

import pandas as pd
df = pd.DataFrame({
u'睦月': [18100, 22000, 6800, 14100],
u'如月': [14600, 29000, 8800, 12100],
u'弥生': [9900, 12000, 13000, 8500]
},
index = [u'山田', u'鈴木', u'佐藤', u'木村']
)

まあ、なんでもいいのだが、月ごとの出費額っぽいダミーのデータだ。

2. 棒グラフ

Notebook を使うがいいのだが、ブログの都合で、コンソールで簡単にチャートが表示されるように ipython を起動する。

$ ipython --pylab=inline

お手軽に棒グラフを書いてみる。

In [4]: df.plot(kind='bar')
Out[4]: <matplotlib.axes.AxesSubplot at 0x111e58f90>


各人の支出額が分かりやすく表示された。次は、データの行列を入れ替えて棒グラフを表示してみる。

In [5]: df.T.plot(kind='bar')
Out[5]: <matplotlib.axes.AxesSubplot at 0x113939e90>


今度は、横軸が陰暦になった。

3. 積み上げ棒グラフ

各人の総額で比べるために、積み上げてみる。

In [6]: df.plot(kind='bar', stacked=True)
Out[6]: <matplotlib.axes.AxesSubplot at 0x11160d350>


先ほどと同様に行列を入れ替えると、月ごとの比較になる。

In [7]: df.T.plot(kind='bar', stacked=True)
Out[7]: <matplotlib.axes.AxesSubplot at 0x1135c70d0>

4. 横向き

横向きにするなら kind を barh にする。

In [8]: df.plot(kind='barh', stacked=True)
Out[8]: <matplotlib.axes.AxesSubplot at 0x113619990>


In [9]: df.T.plot(kind='barh', stacked=True)
Out[9]: <matplotlib.axes.AxesSubplot at 0x113669410>

今回はこんなところで。