FuncAnimation not iterable

2019-09-13 02:54发布

I'd like to create 2 animations and save them to one file, but get the error: TypeError: 'FuncAnimation' object is not iterable

Separately each animation runs fine.

Here's a minimal-ish example that demonstrates the problem. The cosmetic stuff like ax.text and ax.axhline may help show what I'm trying to do, but is not essential to the problem. I'm running the code in a Jupyter notebook.

Thanks for any help.

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

xdata = np.array([0.2, 0.4, 0.6, 0.8])
ydata = np.array([0, 0, 0, 0])

fig = plt.figure(figsize=(8,1.25))
ax = fig.add_subplot(111)
ax.set_xlim(0, 1)
ax.set_ylim(-0.5, 0.5)
ax.barh(0, 1, align='center', height=0.7, color='.95', ec='None', zorder=-20)
ax.axhline(0, 0, 1, color='0.25', linewidth=.5)
ax.text(0, -0.45, "0", verticalalignment = "center", horizontalalignment="center", fontsize=10)
ax.text(1, -0.45, "1", verticalalignment = "center", horizontalalignment="center", fontsize=10)
ax.text(-0.01, 0, "0", verticalalignment = "center", horizontalalignment="center", fontsize=10)
ax.text(0.75, -0.45, "3/4", verticalalignment = "center", horizontalalignment="center", fontsize=10)
ax.axvline(0.75, 0.15, 0.85, color='.5', linestyle='dotted', linewidth=0.75)

line, = ax.plot(xdata, ydata, 'ro', markersize=7)

def init0():     # initialization function for first animation
    line.set_data(xdata, ydata)
    return line,

def init1():     # second animation
    ax.set_xlim(0.5, 1)
    ax.text(0.5, -0.45, "1/2", verticalalignment = "center", horizontalalignment="center", fontsize=10)
    line.set_data(xdata, ydata)
    return line,

def animate(i):     # update function
    ax.figure.canvas.draw()
    return line,

# call animators
anim0 = animation.FuncAnimation(fig, animate, init_func=init0, frames=150, interval=20, blit=True)
anim1 = animation.FuncAnimation(fig, animate, init_func=init1, frames=150, interval=20, blit=True)


fig.set_size_inches(16, 2.5, True)     # improve resolution in animation
plt.axis('off')

anim0.save('anims.mp4', fps=30, extra_args=['-vcodec', 'libx264'], extra_anim=anim1)
plt.show()

0条回答
登录 后发表回答