Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a single frame is generated by the code below:

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 do I define the functions init() and animate() such that I can produce an animation using e.g.:

animation.FuncAnimation(fig, animate, initfunc=init,interval=200, blit=True)
like image 423
BeMuSeD Avatar asked Nov 14 '13 15:11

BeMuSeD


People also ask

How do I show an animation in Matplotlib?

Animations in Matplotlib can be made by using the Animation class in two ways: By calling a function over and over: It uses a predefined function which when ran again and again creates an animation. By using fixed objects: Some animated artistic objects when combined with others yield an animation scene.

What is a patch in Matplotlib?

The matplotlib. patches. Rectangle class is used to rectangle patch to a plot with lower left at xy = (x, y) with specified width, height and rotation angle.

What is Blit in FuncAnimation?

blit=True means only re-draw the parts that have changed. anim = animation. FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) # save the animation as an mp4. This requires ffmpeg or mencoder to be # installed.


1 Answers

You can change to color of the circles in an animation like this:

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()
like image 65
Molly Avatar answered Sep 21 '22 13:09

Molly