Matplotlib动画仅使用ffmpeg

时间:2016-10-25 13:38:24

标签: python animation matplotlib

我对Python Matplotlib动画有一个奇怪的问题。我想制作一个视频,其中包括角落中的另一个小视频:较大的绘图应该为某些数据设置动画,而小插入的绘图应该用移动的虚线指示全局数据图上的时间位置。当我只使用plot.show()时,一切正常,就像我想要的那样。但是当我评论plot.show()并试图用ani.save保存它时,所有它保存的都是一个很大的情节,插入的那个就消失了!

如果我同时尝试取消注释ani.save和plot.show(),我会收到一条错误消息“AttributeError:draw_artist只能在缓存渲染的初始绘制后使用”,以及动画屏幕只是留空。

你能帮我解决一下吗?我需要一个保存完整的电影文件。

以下是代码:

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

Q_data = np.arange(100.).reshape((10,10))
age = np.arange(10.)
Q_total = np.arange(10.)

Q = Q_data[1:,:] 
r_ax = np.arange(10.)


fig, ax = plt.subplots()
line, = ax.semilogy(r_ax,Q[0,:])
time_template = 'time = %.1f'
time_text = ax.text(0.58, 0.9, '', size=20, transform=ax.transAxes)
plt.title('Plot 1')
ax.set_xlabel('Axis Title')
ax.set_ylabel('Axis Title')
# this is another inset axes over the main axes    
a = plt.axes([0.2, 0.5, .3, .3])
line2, = plt.semilogx(age,Q_total,color='r',linewidth=1)    
plt.title('Plot 2', y=1.11)
a.set_xlabel('Small axis title')
#fig.canvas.draw()

def animate(i):
    line.set_ydata(Q[i,:])  # update the data
    time_text.set_text(time_template % (age[i])) 
    a.lines.pop()
    a.semilogx(age,Q_total,color='r',linewidth=1)  
    a.axvline(age[i], color='k', linestyle='--', linewidth=1)        


    return line, a, time_text

# Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(r_ax, mask=True))
    time_text.set_text('')
    return line, time_text    


ani = animation.FuncAnimation(fig, animate, np.arange(1, Q.shape[0], 1),     init_func=init, interval=25, blit=True)

ani.save('testanimation.avi', writer="ffmpeg", fps=15)                                 

plt.show()

1 个答案:

答案 0 :(得分:0)

我给你做了一个小轴和小轴内的小例子。

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['animation.ffmpeg_path'] = r'D:\ffmpeg-20161029-1e660fe-win64-static\bin\ffmpeg.exe'
import matplotlib.animation as animation

r_ax = np.arange(1, 10., 0.1)

fig, ax = plt.subplots()
line, = ax.plot(r_ax, np.log(r_ax))
a = plt.axes([0.2, 0.5, .3, .3])
line2, = a.plot([], [],color='r',linewidth=1)
a.set_xlim([1, 10])
a.set_ylim([0, 3])

def animate(i):
    line.set_data(r_ax[:i], np.log(r_ax[:i]))  # update the data
    line2.set_data(r_ax[:i], 3-np.log(r_ax[:i]))

    return line, line2

ani = animation.FuncAnimation(fig, animate, frames=100, interval=35, blit=True)
ani.save('testanimation.avi', writer="ffmpeg", fps=15)

# plt.show()