2017-11-14 15 views
1

私はArtistAnimationでアニメーションサブプロットを描画したいと思います。残念ながら、私はアニメ伝説を持つ方法を把握することはできません。 StackOverflowで見つけたさまざまな方法を試しました。私が伝説を得ることができれば、それはアニメ化されず、すべてのアニメーションステップの伝説だけで一緒になります。サブプロットのアニメーション凡例の描画方法は?

私のコードは次のようになります。

import numpy as np 
import pylab as pl 
import matplotlib.animation as anim 

fig, (ax1, ax2, ax3) = pl.subplots(1,3,figsize=(11,4)) 
ims = [] 
im1 = ['im11','im12','im13'] 
im2 = ['im21','im22','im23'] 
x = np.arange(0,2*np.pi,0.1) 

n=50 
for i in range(n): 
    for sp in (1,2,3): 
     pl.subplot(1,3,sp) 

     y1 = np.sin(sp*x + i*np.pi/n) 
     y2 = np.cos(sp*x + i*np.pi/n) 

     im1[sp-1], = pl.plot(x,y1) 
     im2[sp-1], = pl.plot(x,y2) 

     pl.xlim([0,2*np.pi]) 
     pl.ylim([-1,1]) 

     lab = 'i='+str(i)+', sp='+str(sp) 
     im1[sp-1].set_label([lab]) 
     pl.legend(loc=2, prop={'size': 6}).draw_frame(False) 

    ims.append([ im1[0],im1[1],im1[2], im2[0],im2[1],im2[2] ]) 

ani = anim.ArtistAnimation(fig,ims,blit=True) 
pl.show() 

This is how the result looks like

が、私はこのコードは How to add legend/label in python animationここで使用される方法に相当するだろうと思ったけど、明らかに、私は何かが欠けています。

また、Add a legend for an animation (of Artists) in matplotlibに示唆されているようにラベルを設定しようとしましたが、私のケースでどのように使用するのか分かりません。このように

im2[sp-1].legend(handles='-', labels=[lab]) 

AttributeError: 'Line2D' object has no attribute 'legend'となります。

[編集]:私はそれを明確に述べていませんでした。私はプロット内に両方の行の伝説がありたいと思います。

答えて

1

凡例がどのように表示されるべきかはわかりませんが、現在のフレームから1行の現在の値を表示させたいと思っています。したがって、150個の新しいプロットをプロットするのではなく、ラインのデータを更新する方がよいでしょう。

import numpy as np 
import pylab as plt 
import matplotlib.animation as anim 

fig, axes = plt.subplots(1,3,figsize=(8,3)) 
ims = [] 
im1 = [ax.plot([],[], label="label")[0] for ax in axes] 
im2 = [ax.plot([],[], label="label")[0] for ax in axes] 
x = np.arange(0,2*np.pi,0.1) 

legs = [ax.legend(loc=2, prop={'size': 6}) for ax in axes] 

for ax in axes: 
    ax.set_xlim([0,2*np.pi]) 
    ax.set_ylim([-1,1]) 
plt.tight_layout() 
n=50 
def update(i): 
    for sp in range(3): 
     y1 = np.sin((sp+1)*x + (i)*np.pi/n) 
     y2 = np.cos((sp+1)*x + (i)*np.pi/n) 

     im1[sp].set_data(x,y1) 
     im2[sp].set_data(x,y2) 

     lab = 'i='+str(i)+', sp='+str(sp+1) 
     legs[sp].texts[0].set_text(lab) 
     legs[sp].texts[1].set_text(lab) 

    return im1 + im2 +legs 

ani = anim.FuncAnimation(fig,update, frames=n,blit=True) 
plt.show() 

enter image description here

+0

私の最小限の例では、少しも最小であったようです。 :) 私は両方の行の伝説が欲しいです。 'legs2'を追加して手作業で良い位置に移動することはできますが、自動的に2番目のデータ(ここではオレンジ色)には関連付けられません。 現実には、私は30000 'i'sのデータを扱っており、それらのほとんどをスキップしなければならないので、(defを使う代わりに)ループバージョンを好んでいました。 'update(i)'に 'continue'や' break'のようなものを含める方法はありますか? – Waterkant

+1

'frames = something'によって与えられる' i'で 'update'関数を呼び出すことは' for i in something'というループと同じです。したがって、私はそれに何ら問題は見ません。もちろん、上記のコードからArtistAnimationを実行することもできます。リストのアーティストにリストを追加するだけです。私は2つの凡例を使って答えを更新しました。 – ImportanceOfBeingErnest

+0

私はそれをArtistAnimationと連携させることはできませんでしたが、包括的なリストで 'frames = n'を使用していました。ありがとう! – Waterkant

関連する問題