Matplotlib 简单动画

我的github链接

(1)关键函数

需要实现两个函数:func和init_func。

animation.FuncAnimation(fig=fig,        # 绘制动画的figure
                        func=animate,     # 更新函数
                        frames=100,       # iterator。 若整数会化成range(100)。 每个值会传入到func。 
                        init_func=init,   # 初始化函数。 自定义开始帧。
                        interval=20,      # 间隔 ms
                        blit=False)    

(2)示例

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


# 制造数据,10个
x = np.arange(10)
anim_frames = []   # (20,2,10) ,20 frames ,2 lines 
for i in range(20):
    anim_frames.append([np.arange(10)+i,np.arange(10)+2.5*i+0.7])
anim_frames = np.asarray(anim_frames)
print(anim_frames)
print(anim_frames.shape)



# 绘制动画
fig, ax = plt.subplots()
line_a, = ax.plot([], [], 'r-', label='test_a')
line_b, = ax.plot([], [], label='test_b')
frame_number = ax.text(0.05,0.95,'',transform=ax.transAxes) 
ax.legend()

def init():
    ax.set_xlim(-1,12)
    ax.set_ylim(0, 40)
    line_a.set_data(x, np.arange(10))
    line_b.set_data(x, 2*np.arange(10))
    frame_number.set_text('')
    return (line_a, line_b,frame_number)

def update(index):     # 在range(10)的循环中会调用该函数,值为0-9。 
    frame_number.set_text(
        'Frame: {}/{}'.format(index+1, len(anim_frames))
    )
    y_a,y_b = anim_frames[index]
    line_a.set_data(x, y_a)
    line_b.set_data(x, y_b)
    return (line_a, line_b,frame_number)

anim = FuncAnimation(fig, update, frames=range(len(anim_frames)),init_func=init, blit=True)
anim.save('anim.gif', writer='imagemagick', fps=12)   # dpi=1000
plt.show()

(3)结果

gif

(4)相关链接

  1. matplotlib.animation.FuncAnimation
  2. matplotlib.axes.Axes.text
  3. 我忘记要不要安装imagemagick了,可以参考教程
  4. 更多示例

猜你喜欢

转载自www.cnblogs.com/zayinhe17/p/9450969.html