目次
棒グラフを作成する (1)
棒グラフ (bar chart) を作成するためには、
matplotlib.pyplot モジュールの bar 関数を使います。
ここで、bar 関数の必須な引数は
x,
height の 2 つです。
- x: 各棒のx座標を表すシーケンス
- height: 各棒の高さを表すシーケンス、または数値
オプション引数については、まず
width,
bottom
が有ります。
更にキーワード専用引数と可変長キーワード引数については、
align,
tick_label,
color,
facecolor,
edgecolor,
linewidth
などが有ります。
- width: 各棒の幅を表す数値、またはシーケンス
- bottom: 各棒の基準となるy座標を表すシーケンス、または数値
- align: 各棒の配置方法で値は "center" または "edge"
- tick_label: x軸目盛りのラベル名を表すシーケンス、または文字列
- color: 縁と塗りつぶしの色
- facecolor (fc): 塗りつぶしの色
- edgecolor (ec): 縁の色
- linewidth (lw): 縁の太さ
Example
source code
from matplotlib import pyplot
x = [1, 2, 3, 4]
values = [10, 20, 5, 25]
width = 0.2
pyplot.bar(x, values, width)
pyplot.savefig("bar_chart.png")
result
棒グラフを作成する (2)
Axes オブジェクトの bar メソッドを使うことでも、
棒グラフを作成することができます。
Example
source code
from matplotlib import pyplot
x = [1, 2, 3, 4]
values = [10, 20, 5, 25]
fig = pyplot.figure()
ax = fig.add_subplot(1, 1, 1)
width=0.2
ax.bar(x, values, width)
pyplot.savefig("bar_chart.png")
result
「棒グラフを作成する (1)」と同様。
棒グラフの書式を変更する
下記のいずれかの方法で、棒グラフの書式を変更することができます。
- barメソッドを使う時に、 任意のプロパティをキーワード引数として指定する
- matplotlib.pyplotモジュールの- setp関数で、 「- barメソッドで取得した- BarContainerの- Rectangleオブジェクト」と、 任意のプロパティをキーワード引数として指定する
- 「barで取得したBarContainerのRectangleオブジェクト」の任意のメソッドを使う- set_facecolor: 塗りつぶしの色
- set_edgecolor: 縁の色
- set_linewidth: 縁の太さ
 
Example A
source code
from matplotlib import pyplot
x = [1, 2, 3, 4]
values = [10, 20, 5, 25]
fig = pyplot.figure()
ax = fig.add_subplot(1, 1, 1)
ax.bar(x, values, 0.2, facecolor="c",
                       edgecolor="blue",
                       linewidth=5.5)
pyplot.savefig("bar_chart_format_a.png")
result
Example B
source code
from matplotlib import pyplot
x = [1, 2]
values = [10, 20]
fig = pyplot.figure()
ax = fig.add_subplot(1, 1, 1)
bars = ax.bar(x, values, width=[0.4, 0.2])
pyplot.setp(bars[0], fc="#ffff00",
                     ec="forestgreen",
                     lw=2.5)
bars[1].set_facecolor("plum")
bars[1].set_edgecolor("darkorchid")
bars[1].set_linewidth(7.5)
pyplot.savefig("bar_chart_format_b.png")
result
積み上げ棒グラフを作成する
積み上げ棒グラフを作成するには、
次のような手順で bar メソッドを使うことで実現できます。
- 「下から1番目の棒」を作成する時は、bottomを指定しない (もしくはbottom=0)
- 「下から2番目の棒」を作成する時は、bottomに「下から1番目の棒の高さ」を指定する
- 「下から3番目の棒」を作成する時は、bottomに「下から1番目と2番目の棒の高さの合計」を指定する
Example
source code
import numpy
from matplotlib import pyplot
x = [1, 2, 3, 4]
values1 = numpy.array([10, 20, 15, 25])
values2 = numpy.array([30, 25, 20, 15])
values3 = numpy.array([5, 10, 15, 20])
fig = pyplot.figure()
ax = fig.add_subplot(1, 1, 1)
ax.bar(x, values1, 0.2)
bottom = values1
ax.bar(x, values2, 0.2, bottom)
bottom = values1 + values2
ax.bar(x, values3, 0.2, bottom)
pyplot.savefig("stacked_bar_chart.png")