2

I'm trying out some animating with python and found something weird while working through the "Animation" part of this tutorial. Relevant code:

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

fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(7, 6.5)

ax = plt.axes(xlim=(0, 10), ylim=(0, 10))
patch = plt.Circle((5, -5), 0.75, fc='y')

def init():
    patch.center = (5, 5)
    ax.add_patch(patch)
    return patch,

def animate(i):
    x, y = patch.center
    x = 5 + 3 * np.sin(np.radians(i))
    y = 5 + 3 * np.cos(np.radians(i))
    patch.center = (x, y)
    return patch,

anim = animation.FuncAnimation(fig, animate, 
                               init_func=init, 
                               frames=360, 
                               interval=20,
                               blit=True)

plt.show()

On my pc the python script showed two circles instead of one, with one of them being fixed at (5,5). After some searching I figured out that the init() function gets called two times. This seems to happen consistently - I added a print "test" call to the init() function of the simple_anim script from the matplotlib examples like this:

def init():
    print "test"
    line.set_ydata(np.ma.array(x, mask=True))
    return line,

and got

pedsb@pedsb:~/shook_/PSM.Application.Simulation$ python simple_anim.py 
test
test

Is this an intended behaviour? How can I fix the code from the tutorial so it only shows one circle? I can set the initial patch.center to somewhere off-screen, but I don't really like that "solution".

jbindel
  • 5,535
  • 2
  • 25
  • 38
Simon
  • 63
  • 4
  • 2
    init sets up what the base-line canvas should look like for blitting. You should not have any artists shown in `init` that you want to animate. – tacaswell Mar 04 '14 at 17:04
  • Anyway, on my machine, both in your code and in the linkes example, `test` appears only once after adding the `print 'test'` in the init() – gg349 Mar 04 '14 at 17:06
  • I played around with it a lot today, but I could not figure out why the `init` gets called two times. I then added a global `initialized` flag as a work around. The circle would still show though, but setting `blit=False` in `FuncAnimation` resolved this. But afaik it should also be working with `blit=True`. Anyway, I'm using pygame now which works without problems, so I won't try to fix this anymore. But thanks for the comments! – Simon Mar 05 '14 at 15:25

0 Answers0