Animating patch objects in python / matplotlib

I am trying to animate an array of circles so that they change color over time. An example of one frame is generated by the following code:

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

nx = 20
ny = 20

fig = plt.figure()
plt.axis([0,nx,0,ny])
ax = plt.gca()
ax.set_aspect(1)

for x in range(0,nx):
    for y in range(0,ny):
        ax.add_patch( plt.Circle((x+0.5,y+0.5),0.45,color='r') )

plt.show()

How to define the init () and animate () functions so that I can create an animation using, for example:

animation.FuncAnimation(fig, animate, initfunc=init,interval=200, blit=True)
+4
source share
1 answer

You can change the color of the circles in the animation as follows:

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

nx = 20
ny = 20

fig = plt.figure()
plt.axis([0,nx,0,ny])
ax = plt.gca()
ax.set_aspect(1)

def init():
    # initialize an empty list of cirlces
    return []

def animate(i):
    # draw circles, select to color for the circles based on the input argument i. 
    someColors = ['r', 'b', 'g', 'm', 'y']
    patches = []
    for x in range(0,nx):
        for y in range(0,ny):
            patches.append(ax.add_patch( plt.Circle((x+0.5,y+0.5),0.45,color=someColors[i % 5]) ))
    return patches

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=10, interval=20, blit=True)
plt.show()
+6
source

All Articles