Python에서 플롯 애니메이션

Feb 24 2023
이 기사에서는 Matplotlib를 사용하여 Python에서 플롯을 애니메이션으로 만드는 방법을 보여주므로 시각화에 멋진 터치를 추가할 수 있습니다! Matplotlib Matplotlib는 Python 프로그래밍 언어용 플로팅 패키지입니다. Python에서 시각화를 위한 가장 인기 있는 패키지 중 하나이며 사용자에게 2D, 3D 및 애니메이션 플롯을 생성할 수 있는 기능을 제공합니다.

이 기사에서는 Python에서 Matplotlib를 사용하여 플롯을 애니메이션하는 방법을 보여주므로 시각화에 멋진 터치를 추가할 수 있습니다!

Matplotlib 로고

Matplotlib

Matplotlib는 Python 프로그래밍 언어용 플로팅 패키지입니다. Python에서 시각화를 위한 가장 인기 있는 패키지 중 하나이며 사용자에게 2D, 3D 및 애니메이션 플롯을 생성할 수 있는 기능을 제공합니다. Matplotlib는 선 플롯, 산점도, 막대 차트 및 히스토그램을 포함하여 플롯을 생성하기 위한 다양한 사용자 정의 옵션을 제공합니다. 많은 사람들이 정적 시각화를 위해 Matplotlib을 사용하는 데 이미 익숙하기 때문에 애니메이션 플롯에 대한 사용법을 다룰 것입니다. Matplotlib를 처음 사용하지만 Python에 이미 익숙한 사용자를 위해 여기 패키지를 시작하는 데 유용한 리소스가 있습니다.

기본 2D 애니메이션 플롯

#Empty lists for X/Y data
x = []
y = []

#Create a figure and axis to plot on
fig, ax = plt.subplots()


#We will create a function that will be called by Matplotlib's FuncAnimation
def getAnimation(iterator):
    newInt = random.randint(1,10)
    #Append values to our lists
    x.append(iterator)
    y.append(newInt)
    
    #Clear previous data from the plot
    ax.clear()
    #Plot the lists with axis limits
    ax.plot(x, y)
    ax.set_xlim([0,20])
    ax.set_ylim([0,20])
    
    
#We pass FuncAnimation our getAnimation function so that it is called in a loop
animation = FuncAnimation(fig, getAnimation, frames=20, 
            interval=500, repeat=False)

plt.show()

Matplotlib를 통해 제공되는 FuncAnimation()은 일정 수의 프레임으로 루프에서 실행될 Figure와 함수가 필요합니다. 인수로 getAnimation()을 전달함으로써 기본적으로 여러 프레임을 반복 하면서 애니메이션을 형성하기 위해 결합되는 플롯의 슬라이드쇼를 생성합니다. 이것은 우리 코드의 결과입니다…

각 x값에 대해 임의의 y값을 플로팅하는 기본 애니메이션

임의의 3D 걷기 애니메이션

#Empty lists for X/Y/Z data
x = []
y = []
z = []

#Lets start off at (10,10,10) the center of our figure with axis limits 20
x.append(10)
y.append(10)
z.append(10)

#Total number of steps we will take
stepTotal = 20

#Create a figure and axis to plot on (3-D)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")

#We will create a function that will be called by Matplotlib's FuncAnimation
def randomWalk(step):
    
    #Append values to our lists
    x.append(random.uniform(1,10))
    y.append(random.uniform(1,10))
    z.append(random.uniform(1,10))
    
    #Clear previous data from the plot
    ax.clear()
    #Plot the lists with axis limits
    ax.plot(x, y, z)
    ax.set_xlim([0,20])
    ax.set_ylim([0,20])
    ax.set_zlim([0,20])
    

# Creating the Animation object
animation = FuncAnimation(fig, randomWalk, frames=stepTotal, interval=100)

plt.show()

3D 공간에서 무작위로 걷는다.

애니메이션 저장


#FuncAnimation() returns an animation object that can be stored
animation = FuncAnimation()

#Instantiate the directory you wish to save to
directory = "/medium/animation.gif"

#We call .save() on our animation object and pass the function a directory
animation.save(directory)

이 기사의 모든 코드는 내 Github 에서 찾을 수 있습니다 .

이 미디엄 기사가 흥미로웠다면 저를 팔로우해 보세요! 나는 수학, 컴퓨터 과학 및 그 사이의 모든 것에 대해 글을 씁니다!