차밍이

[Python] Scatter Plot Animation - 영상 그래프 제작 본문

파이썬/기본 문법 정리

[Python] Scatter Plot Animation - 영상 그래프 제작

2022. 4. 21. 18:53
반응형

Scatter Plot Animation

matplotlib.animation.FuncAnimation

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, , *cache_frame_data=True, *kwargs*)

def func(frame, *fargs) -> iterable_of_artists

matplotlib에서도 애니메이션 형식으로 움직이는 그래프를 그려줄 수 있다.

그림을 그려줄 fig객체와 시간에 따라 변화하는 데이터의 변화를 어떻게 정의할 것인지에 대한 함수(func)가 필요하다.

보통 matplotlib 에니메이션 관련해서 검색하면 전체 데이터를 뿌려주고 해당 점들이 움직이는 모습에 대해서만 나온다.

그래서 그래프에 scatter 점이 하나씩 늘어나는 방식의 코드가 필요해서 가져왔다.

 

Source Code

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

fig, ax = plt.subplots()
x, y = [],[]
sc = ax.scatter(x,y)
plt.xlim(0,10)
plt.ylim(0,10)

def animate(i):
    x.append(np.random.rand(1)*10)
    y.append(np.random.rand(1)*10)
    sc.set_offsets(np.c_[x,y])

ani = matplotlib.animation.FuncAnimation(fig, animate, 
                frames=10, interval=100, repeat=True) 

ani.save('out2.gif')
plt.show()

 

반응형

관련된 글 보기

Comments