2017-11-14 17 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

정확히 전설이 어떻게 생겼는지는 모르겠지만 현재 프레임에서 한 줄의 현재 값을 표시하기를 원합니다. 따라서 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'를 추가하고 그것을 수동으로 좋은 위치로 옮길 수는 있지만 두번째 (여기서는 주황색) 데이터와 자동으로 연결되지 않습니다. 지금까지 루프 버전 ('def' 대신에)을 선호했습니다. 왜냐하면 현실에서는 30000'i's의 데이터로 작업하고 있기 때문에 대부분을 건너 뛰어야하기 때문입니다. 'update (i)'에'continue' 나'break' 같은 것을 포함시키는 방법이 있습니까? – Waterkant

+1

'frames = something'에 의해 주어진'i'로'update' 함수를 호출하는 것은'for i in something'과 같은 루프입니다. 그러므로 나는 그것에 어떤 문제도 보이지 않는다. 물론 위의 코드에서 ArtistAnimation을 수행 할 수도 있습니다. 목록 아티스트에게 범례를 추가하기 만하면됩니다. 두 개의 범례 항목으로 답변을 업데이트했습니다. – ImportanceOfBeingErnest

+0

ArtistAnimation과 함께 작동시키지 못했지만 'frames = n'을 사용하여 포괄적 인 목록을 작성했습니다. 감사! – Waterkant