Python Code Notes

Information by python engineer

【matplotlib.pyplot】棒グラフを描画する方法【Python】

f:id:vigilantPotato:20190721115117p:plain
matplotlibで棒グラフを描画する方法を整理する。


【スポンサーリンク】


barメソッドによる棒グラフの描画

グラフ表示するデータの準備

モジュールのインポート及び表示させるグラフのデータは以下の通り。

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = [1, 5, 2, 9, 10]

以下の例では、subplots関数を用いてグラフオブジェクトを生成する。subplots関数を用いたグラフの描画については、以下の記事を参照。

[↑ 目次へ]


barメソッドで棒グラフを描画

subplotsで生成したAxesオブジェクトに対してbarメソッドを実行することで、棒グラフを表示することができる。 xが各棒グラフの横軸の位置、yが棒グラフの高さになる。

fig, ax = plt.subplots()
ax.bar(x, y)
f:id:vigilantPotato:20190721114842p:plain

また、dataオプションを用いることで、辞書型やpandasのDataFrame型の様なデータを扱うことも可能。

data = {"x":x, "y":y}
fig, ax = plt.subplots()
ax.bar("x", "y", data=data)
f:id:vigilantPotato:20190721114855p:plain

[↑ 目次へ]


【スポンサーリンク】


色の設定

colorオプションを用いて、棒グラフを塗りつぶす色を指定することができる。また、edgecolorオプションでは、棒グラフの縁の色の指定が可能。

fig, ax = plt.subplots()
ax.bar(x, y, color="r", edgecolor="g")
f:id:vigilantPotato:20190721114910p:plain

データ長さと同じ長さの色データを準備すれば、棒グラフ一つ一つについても色の設定が可能です。

color=["r", "g", "c", "b", "y"]
fig, ax = plt.subplots()
ax.bar(x, y, color=color)
f:id:vigilantPotato:20190721114926p:plain

[↑ 目次へ]


グラフ幅の設定

widthオプションを用いて、グラフの幅を設定することが可能。 width=1でグラフ間の隙間はなくなる。

fig, ax = plt.subplots()
ax.bar(x, y, width=1)
f:id:vigilantPotato:20190721114938p:plain

データ長さと同じ長さの幅を準備すれば、棒グラフ一つ一つについても幅の設定が可能です。

width=[0.3, 0.4, 0.5, 0.6, 0.7]
fig, ax = plt.subplots()
ax.bar(x, y, width=width)
f:id:vigilantPotato:20190721114956p:plain

[↑ 目次へ]


ハッチングの設定

棒グラフにハッチングを入れる場合は、hatchオプションを設定する。ハッチングは、以下の9種類が設定可能。

ハッチング "/" "\" "|" "-" "+" "o" "O" "." "*"
fig, ax = plt.subplots()
ax.bar(x, y, hatch="/")
f:id:vigilantPotato:20190721115013p:plain

[↑ 目次へ]


【スポンサーリンク】


横方向の棒グラフ

横方向に棒グラフを表示するためには、barメソッドではなくhbarメソッドを使用しり。 barメソッドのverticalオプションでhorizontalを設定しても、エラーが発生するので注意が必要。

fig, ax = plt.subplots()
ax.barh(x, y)
f:id:vigilantPotato:20190721115028p:plain

[↑ 目次へ]


横軸ラベルの設定

tick_labelオプションを設定することで、横軸ラベルを設定できる。

label = ["a", "b", "c", "d", "e"]
fig, ax = plt.subplots()
ax.bar(x, y, tick_label=label)
f:id:vigilantPotato:20190721115047p:plain

[↑ 目次へ]


【スポンサーリンク】


応用

複数の棒グラフを横に並べて表示

各グラフをグラフ幅の分だけずらして表示することで、複数の棒グラフを横に並べて表示することができる。

fig, ax = plt.subplots()
width=0.3
ax.bar(x-width/2, y, width=width, label="a")
ax.bar(x+width/2, y, width=width, label="b")
ax.legend()
f:id:vigilantPotato:20190721115104p:plain

[↑ 目次へ]


複数の棒グラフを積み重ねて表示

棒グラフを積み上げて表示するには、bottomオプションを使用する。 上に積み上げるほうのグラフのbottomオプションに、下のグラフの高さを設定する。

fig, ax = plt.subplots()
ax.bar(x, y, label="a")
ax.bar(x, y, bottom=y, label="b")
ax.legend()
f:id:vigilantPotato:20190721115117p:plain

[↑ 目次へ]


エラーバーを表示

棒グラフにエラーバーを追加するには、xerrオプションまたはyerrオプションを使用する。

yerror=[0.3, 0.1, 0.5, 1.1, 0.2]
fig, ax = plt.subplots()
ax.bar(x, y, yerr=yerror)
f:id:vigilantPotato:20190721115130p:plain

[↑ 目次へ]


【スポンサーリンク】