Search on blog:

Zasada działania FuncAnimation w matplotlib

FuncAnimation przyjmuje jako parametr funkcję np. update_data(liczba) i wykonuje następujące rzeczy:

  1. FuncAnimation wywołuje funkcje init()
  2. numer = 0
  3. FuncAnimation wywołuje funkcje update_data(numer)
  4. update_data() modyfikuje dane na wykresie
  5. ??? FuncAnimation czysci wykres (gdy blit=True) ???
  6. ??? FuncAnimation rysuje nowy wykres (gdy blit=True) ???
  7. FuncAnimation robi przerwę
  8. numer = numer + 1
  9. jeśli numer < max_numer idź do punktu 3.
  10. jeśli repeat jest True idź do punktu 2.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy import sin, cos, pi, radians, degrees

# --- constants ---

# number of animation frames
MAX_FRAMES = 50

# number of points
MAX_POINTS = 10

# --- functions ---

def update_data(frame_number):

    #print('step:', step)

    angle = radians(frame_number*360./MAX_FRAMES)

    # add new point
    points_x.append(0.5*sin(angle))
    points_y.append(0.5*cos(angle))

    # remove last point to keep constant number of points
    if len(points_x) > MAX_POINTS:
        points_x.pop(0)
        points_y.pop(0)

    # new data to plot
    obj.set_data(points_x, points_y)

    # return data to FuncAnimation
    #return obj # it can be tuple if you have more plots
    # ??? it seems that return is not needed

    return None

# --- data ---

# points to draw (as global variables)
points_x = [] #[0.5, 0.4, 0.3, 0.2, 0.1, 0.0]
points_y = [] #[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

# --- main ---

#
fig = plt.figure()

# set view limits
ax = plt.axes()
ax.set_ylim(-1, 1)
ax.set_xlim(-1, 1)

# plot() can draws many plots so it always returns list of plots
# obj1, obj2 = plt.plot([], [], 'ro', [], [], 'bo')

# create empty plot 
obj, = plt.plot([], [], 'ro')

# animation controller - have to be assigned to variable 
anim = animation.FuncAnimation(fig, update_data, MAX_FRAMES, interval=500)#, repeat=False)

# stop repeating animation
#anim.repeat = False

# --- start the engine ---

plt.show()
If you like it
Buy a Coffee