Python

파이선 Matplotlib 코일작도 애니메이션 그래프 예제 III

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

파이선 matplotlib  라이브러리를 사용하여 원점에서 점점 반경이 커지는 파라메터형 곡선 작도를 애니메이션으로 처리해보자. 

https://www.youtube.com/watch?v=0-SVkcP6-y4 

 

위 동영상을 본 후 아나콘다 편집기에서 아래의 코드를 copy & paste 하여 저장 후 실행 해 본 후에 가상환경 base(root)의 Open Terminal에서 coilanimation.py 코드가 저장되어 있는 디렉토리를 찾아 commamd lene 명령 python animation.py 를 싱행한 후에 coil.gif 를 실행하여 애니메이션 결과를 관찰해보자.

 

#coilanimation.py

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
from matplotlib.animation import FuncAnimation, PillowWriter
import numpy as np 
plt.style.use('dark_background')

fig = plt.figure() 
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50)) 
line, = ax.plot([], [], lw=2) 

# initialization function 
def init(): 
# creating an empty plot/frame 
line.set_data([], []) 
return line, 

# lists to store x and y axis points 
xdata, ydata = [], [] 

# animation function 
def animate(i): 
# t is a parameter 
t = 0.1*i 

# x, y values to be plotted 
x = t*np.sin(t) 
y = t*np.cos(t) 

# appending new points to x, y axes points list 
xdata.append(x) 
ydata.append(y) 
line.set_data(xdata, ydata) 
return line, 

# setting a title for the plot 
plt.title('Creating a growing coil with matplotlib!') 
# hiding the axis details 
plt.axis('off') 

# call the animator  
anim = animation.FuncAnimation(fig, animate, init_func=init, 
frames=500, interval=20, blit=True) 

# save the animation as mp4 video file 
anim.save("coil.gif", dpi=300, writer=PillowWriter(fps=25))
plt.show()