Matplotlib legend() 関数
legend()グラフに凡例を追加し、読者が各曲線や各データグループに対応する意味を識別できるようにするために使用します。
関数定義
matplotlib.pyplot.legend(*args, **kwargs) Axes.legend(*args, **kwargs) Figure.legend(*args, **kwargs)
よく使うパラメータの説明
| パラメータ | 型 | 説明 |
|---|---|---|
| loc | str または int | 凡例の位置:'best'(自動)、'upper right'、'upper left'、'lower left'、'lower right'、'right'、'center left'、'center right'、'lower center'、'upper center'、'center'、'outside'(外側) |
| bbox_to_anchor | tuple | 凡例のアンカー座標。loc と組み合わせて正確に配置します。例:(1.05, 1) は凡例を Axes の外側右上に配置します。 |
| ncol | int | 凡例の列数。デフォルトは 1。項目が多い場合は複数列で表示します。 |
| fontsize | int または str | 凡例のフォントサイズ。例:10、'small'、'large' |
| frameon | bool | 凡例の枠を表示するかどうか。デフォルトは True |
| shadow | bool | 影の効果を追加するかどうか |
| title | str | 凡例のタイトル |
| facecolor | color | 凡例の背景色 |
| edgecolor | color | 凡例の枠の色 |
| fancybox | bool | 角丸の枠を使用するかどうか。デフォルトは True |
| markerscale | float | 凡例内のマーカーの、元のマーカーに対する拡大縮小率 |
| handlelength | float | 凡例内の線の長さ |
凡例には、設定された
labelパラメータを持つ Artist のみが表示されます。一般的な方法は、plot()、scatter()、bar() などのプロット関数で直接 label を指定し、その後 legend() を呼び出すことです。
使用例
例1:基本の凡例
実例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(layout='constrained')
# 各曲線の label は自動的に凡例に入ります
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
ax.plot(x, np.sin(x) * np.exp(-x/3), label='damped sin(x)')
ax.legend(loc='upper right') # すべての label を自動的に収集します
ax.set_title('Basic Legend')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(layout='constrained')
# 各曲線の label は自動的に凡例に入ります
ax.plot(x, np.sin(x), label='sin(x)')
ax.plot(x, np.cos(x), label='cos(x)')
ax.plot(x, np.sin(x) * np.exp(-x/3), label='damped sin(x)')
ax.legend(loc='upper right') # すべての label を自動的に収集します
ax.set_title('Basic Legend')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()
例2:グラフの外側に凡例 + 複数列
実例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# 複数の曲線を描画します
for i in range(6):
ax.plot(x, np.sin(x + i * 0.5), label=f'sin(x + {i*0.5:.1f})')
# 凡例を Axes の外側に配置し、2列で表示します
ax.legend(loc='upper left',
bbox_to_anchor=(1.02, 1), # 外側の右上
ncol=2, # 2列で表示
title='Phase Shift',
frameon=True,
fancybox=True,
shadow=True)
ax.set_title('Legend Outside the Plot (ncol=2)')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(8, 4), layout='constrained')
# 複数の曲線を描画します
for i in range(6):
ax.plot(x, np.sin(x + i * 0.5), label=f'sin(x + {i*0.5:.1f})')
# 凡例を Axes の外側に配置し、2列で表示します
ax.legend(loc='upper left',
bbox_to_anchor=(1.02, 1), # 外側の右上
ncol=2, # 2列で表示
title='Phase Shift',
frameon=True,
fancybox=True,
shadow=True)
ax.set_title('Legend Outside the Plot (ncol=2)')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()
例3:凡例の項目をカスタマイズ
実例
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(layout='constrained')
ax.plot(x, np.sin(x), 'b-', linewidth=2)
ax.plot(x, np.cos(x), 'r--', linewidth=2)
# 凡例の項目を手動で指定します(プロットの label とは関連付けられません)
blue_line = mpatches.Patch(color='blue', label='Sine Wave')
red_line = mpatches.Patch(color='red', label='Cosine Wave')
ax.legend(handles=[blue_line, red_line],
loc='upper right',
fontsize=11)
ax.set_title('Custom Legend Handles')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()
import matplotlib.patches as mpatches
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(layout='constrained')
ax.plot(x, np.sin(x), 'b-', linewidth=2)
ax.plot(x, np.cos(x), 'r--', linewidth=2)
# 凡例の項目を手動で指定します(プロットの label とは関連付けられません)
blue_line = mpatches.Patch(color='blue', label='Sine Wave')
red_line = mpatches.Patch(color='red', label='Cosine Wave')
ax.legend(handles=[blue_line, red_line],
loc='upper right',
fontsize=11)
ax.set_title('Custom Legend Handles')
ax.set_xlabel('x')
ax.grid(True, alpha=0.3)
plt.show()
例4:凡例の位置コード早見表
実例
import matplotlib.pyplot as plt
# すべての loc コードに対応する位置を表示します
locations = [
'upper left', 'upper right', 'lower left', 'lower right',
'center left', 'center right', 'lower center', 'upper center',
'center'
]
fig, axes = plt.subplots(3, 3, figsize=(10, 8),
layout='constrained')
axes = axes.flatten()
for ax, loc in zip(axes, locations):
ax.plot([0, 1], [0, 1], 'b-', label='Line A')
ax.plot([0, 1], [1, 0], 'r--', label='Line B')
ax.legend(loc=loc, fontsize=8, title=f'loc="{loc}"')
ax.set_xticks([])
ax.set_yticks([])
fig.suptitle('All legend() Locations', fontsize=14)
plt.show()
# すべての loc コードに対応する位置を表示します
locations = [
'upper left', 'upper right', 'lower left', 'lower right',
'center left', 'center right', 'lower center', 'upper center',
'center'
]
fig, axes = plt.subplots(3, 3, figsize=(10, 8),
layout='constrained')
axes = axes.flatten()
for ax, loc in zip(axes, locations):
ax.plot([0, 1], [0, 1], 'b-', label='Line A')
ax.plot([0, 1], [1, 0], 'r--', label='Line B')
ax.legend(loc=loc, fontsize=8, title=f'loc="{loc}"')
ax.set_xticks([])
ax.set_yticks([])
fig.suptitle('All legend() Locations', fontsize=14)
plt.show()
よくある質問
凡例が表示されない?
プロット関数で設定されているか確認してくださいlabelパラメータ。
呼び出したことを確認してくださいlegend()関数。
一部の Artist を凡例に表示する必要がない場合は、label を空文字列または '_nolegend_' に設定します。
凡例の線スタイルを部分的に変更するには?
を使用してlegend.get_lines()凡例内の線オブジェクトを取得してその属性を変更するか、またはhandler_mapパラメータを使用します。
その他の拡張
Matplotlib リファレンスドキュメント