この記事は何
matplotlibのラベルの表示位置を指定できるloc/bbox_to_anchorの指定例。 各パラメータの詳細についてはドキュメントの matplotlib.pyplot.legend — Matplotlib 3.3.4 documentationの項目を参照。以下の例ではpython3.8.5を使用してます。
出力例
loc
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures) (引用元:matplotlib.pyplot.legend — Matplotlib 3.3.4 documentation)
文字列で場所を指定する、デフォルトではbestで自動的に選ばれる。
import matplotlib.pyplot as plt import itertools from sklearn.datasets import make_moons # プロット用データを作成 data, label = make_moons(noise=0.2, n_samples=2000) x0, y0 = data[label==0,0], data[label==0,1] x1, y1 = data[label==1,0], data[label==1,1] x2, y2 = -1*data[label==1,0], 2*data[label==1,1] # locs locs = { 'best': 0, 'upper right': 1, 'upper left': 2, 'lower left': 3, 'lower right': 4, 'right' : 5, 'center left': 6, 'center right': 7, 'lower center': 8, 'upper center': 9, 'center': 10, } # グラフを描画 plt.figure(figsize=(20, 20)) for index, loc in enumerate(locs): plt.subplot(3, 4, index+1) plt.title(f"loc=({loc})") plt.scatter(x0, y0, label="label-A") plt.scatter(x1, y1, label="label-B") plt.scatter(x2, y2, label="label-C") plt.xlabel("X-LABEL") plt.ylabel("Y-LABEL") plt.legend(loc=loc) plt.tight_layout()
bbox_to_anchor
The bbox_to_anchor keyword gives a great degree of control for manual legend placement. (引用元)
手動で細かい位置調整を行う場合は bbox_to_anchor
パラメータを指定する。
import matplotlib.pyplot as plt import itertools from sklearn.datasets import make_moons # プロット用データを作成 data, label = make_moons(noise=0.2, n_samples=2000) x0, y0 = data[label==0,0], data[label==0,1] x1, y1 = data[label==1,0], data[label==1,1] x2, y2 = -1*data[label==1,0], 2*data[label==1,1] # グラフを描画 index = 1 linsp = np.linspace(0, 1, 5) plt.figure(figsize=(20, 20)) for x, y in itertools.product(linsp, linsp): plt.subplot(5, 5, index) plt.title(f"bbox_to_anchor=({x}, {y})") plt.scatter(x0, y0, label="label-A") plt.scatter(x1, y1, label="label-B") plt.scatter(x2, y2, label="label-C") plt.xlabel("X-LABEL") plt.ylabel("Y-LABEL") plt.legend(bbox_to_anchor=(x, y)) index += 1 plt.tight_layout()