Matplotlibの棒グラフ#

公開日

Matplotlibで棒グラフを出力するには、ax.barを使用します。ax.barの最初の引数に横軸方向の位置、2番目の引数に棒の高さをそれぞれ配列で与えます。

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5]) # 横軸の値
y = np.array([5, 3, 7, 4, 6]) # 棒の高さ

fig, ax = plt.subplots()
ax.bar(x, y)
plt.show()
../_images/cdd90e17636e0ca4f4f5e02a4a840e6b7fc87fe16f620eba77125a814b375560.png

積み上げ棒グラフ#

積み上げ棒グラフを作成する場合、bottomオプションで下になるデータを指定します。

y1 = np.array([5, 3, 7, 4, 5]) # 下側のデータ
y2 = np.array([3, 6, 2, 1, 1]) # 上側のデータ

fig, ax = plt.subplots()
ax.bar(x, y1, label="y1")
ax.bar(x, y2, label="y2", bottom=y1)
ax.legend()
plt.show()
../_images/0f57556861e746bfd8659b234a9b0177f2cc9d2e21a393868365d1b2f8bf466d.png

3つ以上のデータを積み上げる場合、以下のように下になるデータを合計する必要があります。

y3 = np.array([3, 1, 2, 3, 2])

fig, ax = plt.subplots()
ax.bar(x, y1, label="y1")
ax.bar(x, y2, label="y2", bottom=y1)
ax.bar(x, y3, label="y3", bottom=y1+y2)
ax.legend()
plt.show()
../_images/70c5eef463910f28ce3c8fd8610d1385afeb6679f81f503372033c97b3be1d67.png

複数系列の棒グラフ#

複数系列の棒グラフを作成する場合、PandasのDataFrameを使うと便利です。

import pandas as pd

df = pd.DataFrame({"y1": [5, 3, 7, 4],
                   "y2": [3, 6, 2, 1]},
                  index=[1, 2, 3, 4])

df
y1 y2
1 5 3
2 3 6
3 7 2
4 4 1

上のようなDataFrame dfに対し、plot.bar()メソッドを使用します。

fig, ax = plt.subplots()
df.plot.bar(ax=ax)
plt.show()
../_images/f5b44a14db7f0572e5d6b31376223d1fd6ba1590fa28c61ac8c2d027f0bc81db.png

棒の太さ・色を変更する#

棒の太さはwidthオプションで指定します。1が最大(隙間なし)、0が最小となります。また、色はcolorオプションで指定します。

fig, ax = plt.subplots()
ax.bar(x, y, width=1, color="orange")
plt.show()
../_images/cddac2f041e5014147f534333df03ba6077b3d0038421b76b222233979225acb.png
fig, ax = plt.subplots()
ax.bar(x, y, width=0.1, color="green")
plt.show()
../_images/b7c991325fd13cf80bb9ed1885b7be7d90e40c9fea31936579af45d5de8d04fa.png

colorオプションの詳細は以下の記事を参考にして下さい。

Matplotlib 色の書式

以下のようにcolorに色のリストを与えることで、棒ごとに異なる色に指定することも可能です。

fig, ax = plt.subplots()
ax.bar(x, y, color=["blue", "orange", "green", "black", "red"])
plt.show()
../_images/699ce715a709c337d77539946ccb9768dbabdb57ac36cbc71561037d7b102865.png

棒に枠線を付ける#

棒に枠線を付ける場合、枠線の色をedgecolor, 枠線の太さをlinewidthで指定します。

fig, ax = plt.subplots()
ax.bar(x, y, edgecolor="black", linewidth=5)
plt.show()
../_images/f096f6a8adffbbcefec321ef334ee84fa475982eb4be483b533425f42eda0508.png

横軸のラベル#

横軸にラベルを付ける場合、tick_labelオプションにリストやNumPy配列などで与えます。

fig, ax = plt.subplots()
ax.bar(x, y, tick_label=["Jan.", "Feb.", "Mar.", "Apr.", "May."])
plt.show()
../_images/afb13db947433ef830914ba65f7ddb70dfa06d0324b8a98059a66e17fcebe39a.png

横棒グラフ#

横棒グラフを出力するには、ax.barhを使用します。ax.barhの最初の引数が縦軸方向の位置、2番目の引数が棒の長さとなります。

fig, ax = plt.subplots()
ax.barh(x, y)
plt.show()
../_images/05601811edfaf14ed6580703c13fa4ae30b5f79076b8b1e2b995baa68be68c2d.png