TheQuant
TheQuant

Reputation: 49

How to use Matplotlib's animate function?

Can anyone see what exactly is wrong with my code here? I am trying to generate an animated plot of my results to see its evolution over time and the result is just a full plot of my data, rather than an updating animation.

enter image description here

The sampleText.txt file is just a numpy array of size (5000, 1), The first 5 entries of the array are [[-0.01955058],[ 0.00658392[,[-0.00658371],[-0.0061325 ],[-0.0219136 ]]

import matplotlib.animation as animation
import time

fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot()

def animate(i):
    
    x = np.linspace(0, len(dataArray), len(dataArray))
    y = []

    for eachLine in x:
        y.append(eachLine * 10)
            
    ax1.clear()
    ax1.plot(x, y, color = 'red', alpha = 0.5)

ani = animation.FuncAnimation(fig, func = animate)

plt.show()

Upvotes: 1

Views: 1158

Answers (1)

r-beginners
r-beginners

Reputation: 35240

The basis of animation is a mechanism where the animation function sets the values to be changed for the initial graph setting. In this case, the line width is 3, the color is red, and x and y are an empty list. xy data is linked to the number of frames by i in the animation function.

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

fig = plt.figure() 

# marking the x-axis and y-axis 
axis = plt.axes(xlim =(0, 500), ylim =(0, 1000)) 

x = np.linspace(0, 500, 500) 
y = x*2
# initializing a line variable 
line, = axis.plot([], [], lw=2, color='r') 

def animate(i): 
    line.set_data(x[:i], y[:i]) 
    return line, 

anim = FuncAnimation(fig, animate, frames=500, blit=True, repeat=False) 
plt.show()

enter image description here

Upvotes: 2

Related Questions