TL;DR ->
Matplotlib
'sPyPlot
で、余分な変数を作らずに折れ線グラフの凡例を作成するにはどうしたらよいでしょうか。
以下のグラフ作成スクリプトをご検討ください:
if __name__ == '__main__':
PyPlot.plot(total_lengths, sort_times_bubble, 'b-',
total_lengths, sort_times_ins, 'r-',
total_lengths, sort_times_merge_r, 'g+',
total_lengths, sort_times_merge_i, 'p-', )
PyPlot.title("Combined Statistics")
PyPlot.xlabel("Length of list (number)")
PyPlot.ylabel("Time taken (seconds)")
PyPlot.show()
見ての通り、これは matplotlib
's PyPlot
の非常に基本的な使用法です。これは理想的には下のようなグラフを生成します:
特別なことではないのは分かっています。しかし、どのデータがどこにプロットされているのかが不明確です(ソートアルゴリズムのデータを、かかった時間に対して長さをプロットしようとしているのですが、どの線がどの線なのかが分かるようにしたいのです)。したがって、凡例が必要なのですが、以下の例(公式サイトより)を見てください:
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")
handles, labels = ax.get_legend_handles_labels()
# reverse the order
ax.legend(handles[::-1], labels[::-1])
# or sort them by labels
import operator
hl = sorted(zip(handles, labels),
key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)
ax.legend(handles2, labels2)
ax`という追加の変数が必要なことがわかります。どうすれば、この余分な変数を作成することなく、現在のスクリプトのシンプルさを維持したまま、グラフに凡例を追加することができるでしょうか。
plot()](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot)の各コールに
label=を追加し、[
legend(loc='左上')`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend)をコールします。
このサンプルを考えてみましょう(Python 3.8.0でのテスト):
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, "-b", label="sine")
plt.plot(x, y2, "-r", label="cosine")
plt.legend(loc="upper left")
plt.ylim(-1.5, 2.0)
plt.show()
[ここに画像の説明を入力][1]。 このチュートリアルを少し修正したものです: http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html
plt.gca()
でAxesインスタンス( ax
)にアクセスできます。 この場合、使用できます。
plt.gca().legend()
これを行うには、各 plt.plot()
呼び出しでlabel =
キーワードを使用するか、この作業例のように、ラベルをタプルまたは legend
内のリストとして割り当てます。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()
。。
ただし、Axesインスタンスに複数回アクセスする必要がある場合は、変数「ax」に保存することをお勧めします。
ax = plt.gca()
次に、「plt.gca()」の代わりに「ax」を呼び出します。
ここでは、その一例をご紹介します。
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
ax.set_title('ADR vs Rating (CS:GO)')
ax.scatter(x=data[:,0],y=data[:,1],label='Data')
plt.plot(data[:,0], m*data[:,0] + b,color='red',label='Our Fitting
Line')
ax.set_xlabel('ADR')
ax.set_ylabel('Rating')
ax.legend(loc='best')
plt.show()
伝説のある正弦曲線とコサイン曲線の単純なプロット。
使用済み matplotlib.pyplot
。
import math
import matplotlib.pyplot as plt
x=[]
for i in range(-314,314):
x.append(i/100)
ysin=[math.sin(i) for i in x]
ycos=[math.cos(i) for i in x]
plt.plot(x,ysin,label='sin(x)') #specify label for the corresponding curve
plt.plot(x,ycos,label='cos(x)')
plt.xticks([-3.14,-1.57,0,1.57,3.14],['-$\pi$','-$\pi$/2',0,'$\pi$/2','$\pi$'])
plt.legend()
plt.show()
plot callの各引数に、グラフ化する系列に対応するラベルを追加します。
そして、スクリプトの最後に Pyplot.legend()
を追加するだけで、凡例がこれらのラベルを表示するようになります。
カスタム凡例documentationを追加できます。
。 最初= [1、2、4、5、4]。 2番目= [3、4、2、2、3]。 plt.plot(first、 'g--'、second、 'r--')。 plt.legend(['First List'、 'Second List']、loc = 'upper left')。 plt.show()。
。
。。