Matplotlib bar() / barh() 関数
bar()垂直棒グラフを描画するために使用し、barh()水平棒グラフを描画するために使用します。
棒グラフはカテゴリデータの数量比較を表示するために使用され、各カテゴリは1本の棒でその値の大きさを表します。
関数定義
bar() - 垂直棒グラフ
matplotlib.pyplot.bar(x, height, width=0.8, bottom=0, *, align='center',
**kwargs)
barh() - 水平棒グラフ
matplotlib.pyplot.barh(y, width, height=0.8, left=0, *, align='center',
**kwargs)
Axes インターフェース
Axes.bar(x, height, width=0.8, bottom=0, *, align='center', **kwargs) Axes.barh(y, width, height=0.8, left=0, *, align='center', **kwargs)
パラメータ説明
| パラメータ | 型 | 説明 |
|---|---|---|
| x / y | array-like | 棒の位置座標(垂直は x、水平は y) |
| height / width | array-like | 棒の高さ(垂直)または幅(水平)、つまりデータ値 |
| width(bar)/ height(barh) | float または array-like | 棒の幅/高さ、デフォルトは 0.8 |
| bottom / left | float または array-like | 棒の底部の開始位置、デフォルトは 0。積み上げ棒グラフの描画に使用できます。 |
| align | str | 棒と x/y 座標の配置方法:'center'(デフォルト)または 'edge' |
| color | color または list | 棒の色。単一の色または色のリストを指定できます。 |
| edgecolor | color | 棒の枠線の色 |
| linewidth / lw | float | 棒の枠線の幅 |
| tick_label | array-like | 棒の目盛りラベル。x 位置と1対1で対応します。 |
| label | str | 凡例ラベル(グループ化された棒グラフ用) |
| alpha | float | 透明度 |
| hatch | str | 塗りつぶしパターン:'/'、'\'、'|'、'-', '+'、'x'、'o'、'*' |
bar_label() 補足説明
bar_label()棒の上に直接数値ラベルを表示するために使用します。
Axes.bar_label(container, labels=None, *, fmt=None, label_type='edge',
padding=0, **kwargs)
bar() と barh() は、
BarContainerオブジェクトを返します。これを bar_label() に渡すことで数値ラベルを追加できます。これは Matplotlib 3.4+ で推奨される方法です。
使用例
例 1:基本的な垂直棒グラフ
例
import matplotlib.pyplot as plt
# カテゴリのラベルとデータ
categories = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
values = [85, 72, 68, 55, 42]
fig, ax = plt.subplots(layout='constrained')
# 棒グラフを描画
bars = ax.bar(categories, values,
color=['#3498db', '#e74c3c', '#f39c12', '#2E7DCC', '#9b59b6'],
edgecolor='white', linewidth=1)
# 棒の上に数値を表示
ax.bar_label(bars, fmt='%d', padding=3)
ax.set_title('Programming Language Popularity')
ax.set_ylabel('Score')
ax.set_ylim(0, 100)
ax.grid(axis='y', alpha=0.3)
plt.show()
# カテゴリのラベルとデータ
categories = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
values = [85, 72, 68, 55, 42]
fig, ax = plt.subplots(layout='constrained')
# 棒グラフを描画
bars = ax.bar(categories, values,
color=['#3498db', '#e74c3c', '#f39c12', '#2E7DCC', '#9b59b6'],
edgecolor='white', linewidth=1)
# 棒の上に数値を表示
ax.bar_label(bars, fmt='%d', padding=3)
ax.set_title('Programming Language Popularity')
ax.set_ylabel('Score')
ax.set_ylim(0, 100)
ax.grid(axis='y', alpha=0.3)
plt.show()
例 2:グループ化された棒グラフ
例
import matplotlib.pyplot as plt
import numpy as np
# グループデータ
labels = ['Q1', 'Q2', 'Q3', 'Q4']
product_a = [120, 135, 148, 162]
product_b = [90, 105, 115, 130]
x = np.arange(len(labels)) # x 位置:[0, 1, 2, 3]
width = 0.35 # 各棒の幅
fig, ax = plt.subplots(layout='constrained')
# 1つ目のグループの棒(オフセット -width/2)
bars1 = ax.bar(x - width/2, product_a, width,
label='Product A', color='steelblue', edgecolor='white')
# 2つ目のグループの棒(オフセット +width/2)
bars2 = ax.bar(x + width/2, product_b, width,
label='Product B', color='coral', edgecolor='white')
# 数値ラベルを追加
ax.bar_label(bars1, padding=3, fmt='%d')
ax.bar_label(bars2, padding=3, fmt='%d')
ax.set_title('Quarterly Sales Comparison')
ax.set_ylabel('Sales (units)')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
import numpy as np
# グループデータ
labels = ['Q1', 'Q2', 'Q3', 'Q4']
product_a = [120, 135, 148, 162]
product_b = [90, 105, 115, 130]
x = np.arange(len(labels)) # x 位置:[0, 1, 2, 3]
width = 0.35 # 各棒の幅
fig, ax = plt.subplots(layout='constrained')
# 1つ目のグループの棒(オフセット -width/2)
bars1 = ax.bar(x - width/2, product_a, width,
label='Product A', color='steelblue', edgecolor='white')
# 2つ目のグループの棒(オフセット +width/2)
bars2 = ax.bar(x + width/2, product_b, width,
label='Product B', color='coral', edgecolor='white')
# 数値ラベルを追加
ax.bar_label(bars1, padding=3, fmt='%d')
ax.bar_label(bars2, padding=3, fmt='%d')
ax.set_title('Quarterly Sales Comparison')
ax.set_ylabel('Sales (units)')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
例 3:積み上げ棒グラフ
例
import matplotlib.pyplot as plt
categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
income = [5000, 5200, 4800, 5500, 6000]
expense = [3000, 3500, 3200, 4000, 4200]
fig, ax = plt.subplots(layout='constrained')
# 1層目の棒(最下部)
bars_income = ax.bar(categories, income,
label='Income', color='#2E7DCC', edgecolor='white')
# 2層目の棒(1層目の上に積み上げ)
bars_expense = ax.bar(categories, expense, bottom=income,
label='Expense', color='#e74c3c', edgecolor='white')
# ラベルを追加
ax.bar_label(bars_income, label_type='center', fmt='$%d')
ax.bar_label(bars_expense, label_type='center', fmt='$%d')
ax.set_title('Stacked Bar Chart: Monthly Finance')
ax.set_ylabel('Amount ($)')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
categories = ['Jan', 'Feb', 'Mar', 'Apr', 'May']
income = [5000, 5200, 4800, 5500, 6000]
expense = [3000, 3500, 3200, 4000, 4200]
fig, ax = plt.subplots(layout='constrained')
# 1層目の棒(最下部)
bars_income = ax.bar(categories, income,
label='Income', color='#2E7DCC', edgecolor='white')
# 2層目の棒(1層目の上に積み上げ)
bars_expense = ax.bar(categories, expense, bottom=income,
label='Expense', color='#e74c3c', edgecolor='white')
# ラベルを追加
ax.bar_label(bars_income, label_type='center', fmt='$%d')
ax.bar_label(bars_expense, label_type='center', fmt='$%d')
ax.set_title('Stacked Bar Chart: Monthly Finance')
ax.set_ylabel('Amount ($)')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.show()
例 4:水平棒グラフ (barh)
例
import matplotlib.pyplot as plt
tasks = ['Task A', 'Task B', 'Task C', 'Task D', 'Task E']
hours = [12.5, 8.0, 15.3, 6.2, 10.8]
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# 水平棒グラフ
bars = ax.barh(tasks, hours,
color='#3498db', edgecolor='white', height=0.6)
# 棒の端にラベルを追加
ax.bar_label(bars, fmt='%.1f h', padding=5)
ax.set_title('Task Completion Time (Horizontal Bar)')
ax.set_xlabel('Hours')
ax.invert_yaxis() # y 軸を反転して、最初のカテゴリを上部に表示
ax.grid(axis='x', alpha=0.3)
plt.show()
tasks = ['Task A', 'Task B', 'Task C', 'Task D', 'Task E']
hours = [12.5, 8.0, 15.3, 6.2, 10.8]
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# 水平棒グラフ
bars = ax.barh(tasks, hours,
color='#3498db', edgecolor='white', height=0.6)
# 棒の端にラベルを追加
ax.bar_label(bars, fmt='%.1f h', padding=5)
ax.set_title('Task Completion Time (Horizontal Bar)')
ax.set_xlabel('Hours')
ax.invert_yaxis() # y 軸を反転して、最初のカテゴリを上部に表示
ax.grid(axis='x', alpha=0.3)
plt.show()
よくある質問
bar() と barh() の軸の対応関係は?
bar(x, height):x は位置、height が棒の高さ(垂直方向)を決定します。
barh(y, width):y は位置、width が棒の幅(水平方向)を決定します。
パラメータ名が異なることに注意:bar は height、barh は width でデータ値を表します。
グループ化された棒グラフの棒を密着させるには?
将 width各グループの棒の合計幅の逆数に設定し、使用します。align='edge'。
その他の拡張