Python

파이선 Matplotlib animation 라이브러리 애니메이션 그래프 예제 II

coding art 2021. 12. 19. 14:47
728x90

아나콘다 편집기에서 matplotlib  라이브러리를 사용하여 애니메이션되는 화면을 구현해보자. 파이선 에니메이션 예제는 야후나 구글에서검색하면 많은 예제를 구할 수 있지만 그대로 copy & paste 해서 아나콘다에서 실행시키면 정지화면만 얻어지게 된다. 따라서 반드시 아나콘다 Navigator 에서 사용하는 가상환경에서 Open Terminal 하여 아나콘다 프롬프트 창을 열어 파이선 애니메이션 코드가 위치한 폴더를 열어서 command line 방식으로 코드를 실행시켜야 한다.

다음 동영상을 참고하도록 하자.

https://www.youtube.com/watch?v=-aEZlVQFf7E 

matplotlib 라이브러리로 작성하는 그래프의 애니메이션을 위해서는 numpy와 matplotlib 의 pyplot 외에도

추가로 animation 을 불러 들여야 한다.

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

 

matplotlib 의 figure 명령문을 사용하여 그래프 묶음 번호 num=1 로 설정하고 해상도 dpi=100으로 두며 배경색은 color='whit'로 설정한다. 물론 그래프 묶음 번호 num=1에는 subplot 명령을 사용하여 하나 이상의 그래프를 넣을 수도 있다. axes 명려을 사용하여 좌표축과 그 범위를 설정한다.

좌표축 설정이 되면 plot 명령에 의해서 수평좌표와 수직좌표 어레이 리스트 데이터를 준비하고, 라인굵기 즉 line weight 를 설정함과 아울러 라인 색상을 지정하자.

line, 형식의 변수명은 튜플 도는 그 이상의 다소 복잡한 데이터 형식을 의미하는듯하다. 

xlabel ㅁ;ㅊ ylabel 명열을 사용하여 좌표축과 그래프 데이터에 추가하여 가로축 명과 세로축 명을 넣는다.

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure(num=1, dpi=100, facecolor='white')
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2,color='red')
plt.xlabel('time(sec)')
plt.ylabel('y')

 

코드 마지막 부분에 위치하는 FuncAnimation 명령에서 그래프 애니메이션 작업을 위한 수평좌표와 수직좌표 어레이 리스트 데이터를 초기화하고 line, 로 돌려준다.

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

 

코드 마지막 부분에 위치하는 FuncAnimation 명령에서 애니메이션 할 함수와 함수의 변수영역을 계산하여 line, 로 돌려준다. 파라메터로 넘겨주는 argument  i 의 최대값은 FuncAnimation 의 frames 값이 된다. frames=200 에 해당하는 i=200 을 animate(i) 에 입력하면 y = np.sin(2*np.pi*(x-2.0))이 됨을 알 수 있다. x 는 linspace 명령에 의해 0.0~2.0 사이의 값을 가지므로 정확하게 한 주기임을 알 수 있다. 따라서 한번에  0.002 만큼씩 그래프를 작도했다 지웠다를 반복함을 알 수 있다.
# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

 

최종적으로 aimation.FuncAnimation  명령을 실행한다.

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
plt.show()

 

아나콘다 스파이더 편집기 상에서는 그래프의 프레임만 보여주므로 반드시 아나콘다 네비게이터에서 아나콘다 명령 프롬프트 창을 열고 commamd line 명령을 사용하여 실행 시키도록 한다.

 

#animation.py

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure(num=1, dpi=100, facecolor='white')
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2,color='red')
plt.xlabel('time(sec)')
plt.ylabel('y')

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 4, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True)
plt.show()