2016-04-28 27 views
1

私は多くの行を持つファイルin.txtを持っています。 1〜20列(未定義)です。数字が含まれています。matplotlib凡例ボックスの名前を変更するには?

私はこのコード伝説のすべての名称は、 "中"、私は "1" のような名前にしたい、 "2"、「3あるのではなく

y=np.loadtxt('in.txt') 
t=np.arange(len(y))*1 
plt.subplot(211) 
plt.title(r'in') 
plt.grid(1) 
plt.plot(t,y, label = 'in') 
plt.legend(borderpad = 0.1, labelspacing = 0.1) 
plt.show() 

It is what I have now (in this example I have 10 columns in file in.txt)

しかし、でグラフィックを描画(1からnまで、ここでnはin.txtファイルの列の数です)

答えて

1

これは、for-loopの繰り返しで各行をプロットすることで可能です。たとえば、次の代わりに

y = np.random.random((3,5)) # create fake data 
t = np.arange(len(y)) 
plt.subplot(211) 
plt.title(r'in') 
plt.grid(1) 
for col_indx in range(y.shape[1]): 
    plt.plot(t, y[:,col_indx], label = col_indx) 
plt.legend(borderpad = 0.1, labelspacing = 0.1) 
plt.show() 

、と私はあなたの場合には、このソリューションをお勧めします、plt.legendへのコールのオプションの引数を使用することです。このように:

plt.plot(t, y) 
plt.legend(range((len(y))) 

もう少し進んでいきたい場合は、plt.legendのドキュメント文字列をチェックしてください。あなたはゼロから始まるのではなく、1から始まるインデックスを使用してラベル付けを開始したい場合

、あなたが放送を活用しているラベルおよび範囲;-)

+0

THXたくさん。 2番目の変種はOKです。それは私が望むものだ – falazure

0

+1を追加することを忘れないでくださいx/yの場合はplotになりますが、kwargもブロードキャストされません。どちらの

x = np.arange(25) 
y = np.random.rand(25, 6) 


fig, ax = plt.subplots() 
for j, _y in enumerate(y.T, start=1): 
    ax.plot(x, _y, label=str(j)) 
ax.legend(borderpad=0.1, labelspacing=0.1) 

または

fig, ax = plt.subplots() 
lns = ax.plot(x, y) 
labels = [str(j) for j in range(1, y.shape[1] + 1)] 
ax.legend(handles=lns, labels=labels, borderpad=0.1, labelspacing=0.1) 
関連する問題