plt.legend() matplotlib by python で凡例

. label=キーワード引数を使う場合

プロットをする際にlabel=キーワード引数で結びつけるラベルを渡すことができます。 結びつけたら、あとはplt.legend関数を呼び出すだけで凡例がグラフにプロットされます。

x = np.linspace(0, 10)
y_sin = np.sin(x)
y_cos = np.cos(x)

plt.plot(x, y_sin, label="sin")
plt.plot(x, y_cos, label="cos")
plt.legend()  # 凡例をグラフにプロット

f:id:bicycle1885:20140501222235p:plain

2. plt.legend()関数でartistとラベルを対応付ける

plt.plot()関数はArtistクラスのインスタンスのリストを返します。 これを受け取ってplt.legend()関数に渡すことでもラベルを結びつけることができます。

p1, = plt.plot(x, y_sin)
p2, = plt.plot(x, y_cos)
plt.legend([p1, p2], ["sin", "cos"])

f:id:bicycle1885:20140501222235p:plain

以下のことが成立することを確かめておきましょう。

assert isinstance(p1, matplotlib.artist.Artist)

凡例の位置調節

凡例の位置が他のプロットとかぶってしまう場合にはloc=キーワード引数を渡すことで 好きな位置に移すことができます。

プロットと被る

x = np.random.randn(100)
y1 = x + np.random.randn(100)
y2 = x * 3 + np.random.randn(100)
plt.plot(x, y1, "r.", label="label 1")
plt.plot(x, y2, "k.", label="label 2")
plt.legend()

f:id:bicycle1885:20140501222346p:plain

凡例の位置を左上(upper left)に置く

plt.plot(x, y1, "r.", label="label 1")
plt.plot(x, y2, "k.", label="label 2")
plt.legend(loc="upper left")

f:id:bicycle1885:20140501222409p:plain

あるいは右下(lower right)に置く

plt.plot(x, y1, "r.", label="label 1")
plt.plot(x, y2, "k.", label="label 2")
plt.legend(loc="lower right")

f:id:bicycle1885:20140501222425p:plain