plt.legend()をつかいます。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, np.pi * 2, 0.1)
plt.plot(x, np.sin(x), color = [1, 0, 0], label = 'sin(x)')
plt.plot(x, np.cos(x), color = [0, 0, 1], label = 'cos(x)')
plt.plot(x, np.exp(-x), color = [0, 0.5, 0], label = 'exp(-x)')
plt.legend()
ここからは少しマニアックです。
こんなことがあるかもしれません。粗い実験データにキレイな理論線を重ねたいとき、実験データの裏に理論線を書きたいとします。するとだいたいこういう風に書きます。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, np.pi * 2, 0.2)
dat = np.sin(x) + (np.random.rand(len(x)) - 0.5) / 5
plt.plot(x, np.sin(x), color = [0, 0, 1], label = 'theory')
plt.plot(x, dat, color = [1, 0, 0], label = 'experiment', marker = 'o', lw = 0, markerfacecolor = [1, 1, 1])
plt.legend()
legendをみるとtheoryがうえで、experimentが下です。theoryの線を裏に置くために先に書いたので、legendの順もそうなっています。でもあなたは実験家で実験のlegendを先に示したいと思っています。そのときは少し複雑ですが・・・
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, np.pi * 2, 0.2)
dat = np.sin(x) + (np.random.rand(len(x)) - 0.5) / 5
plt.plot(x, np.sin(x), color = [0, 0, 1], label = 'theory1')
plt.plot(x, -np.cos(x)*0.5, color = [0, 0.6, 0], label = 'theory2')
plt.plot(x, dat, color = [1, 0, 0], label = 'experiment', marker = 'o', lw = 0, markerfacecolor = [1, 1, 1])
handles, labels = plt.gca().get_legend_handles_labels()
order = [2, 1, 0]
plt.legend([handles[idx] for idx in order],[labels[idx] for idx in order]
, loc = [0.65, 0.7]
, fontsize = 12
)
とするとこんな感じにうまくいきます。

コメント
コメントを投稿