Time for action – animating plots

We will plot three random datasets and display them as circles, dots, and triangles. However, we will only update two of those datasets with random values.

  1. We will plot 3 random datasets as circles, dots and triangles in different colors.
    circles, triangles, dots = ax.plot(x, 'ro’, y, 'g^’, z, 'b.’)
  2. This function will get called to update the screen regularly. We will update two of the plots with new y values.
    def update(data):
        circles.set_ydata(data[0])
        triangles.set_ydata(data[1])
        return circles, triangles
  3. We will generate random data with NumPy.
    def generate():
        while True: yield np.random.rand(2, N)

    Here is a snapshot of the animation in action:

    Time for action – animating plots

What just happened?

We created an animation of random data points (see animation.py):

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

fig = plt.figure()
ax = fig.add_subplot(111)
N = 10
x = np.random.rand(N)
y = np.random.rand(N)
z = np.random.rand(N)
circles, triangles, dots = ax.plot(x, 'ro’, y, 'g^’, z, 'b.’)
ax.set_ylim(0, 1)
plt.axis('off’)

def update(data):
    circles.set_ydata(data[0])
    triangles.set_ydata(data[1])
    return circles, triangles

def generate():
    while True: yield np.random.rand(2, N)

anim = animation.FuncAnimation(fig, update, generate, interval=150)
plt.show()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset