matplotlib FuncAnimation 简单绘制动态图 一个动点

使用matplotlib库可以快速地绘制一些动图,非常方便,为了使用这些,需要import

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

核心类就是

animation.FuncAnimation

这里提供animation.FuncAnimation一些构造的参数:

fig 	  : 画布对象 
func 	  : 更新函数,这个函数的入口是当前帧,方便用户更新点
init_func : 初始化函数,每次动画开始时调用
frames	  : 一次循环包含的帧序列,这个序列会被依次传入func更新函数中
interval  : 迭代时间间隔(ms),越小越快

为了初始化一个动点动画,我们需要以下几个步骤

创建点序列,这些序列将会是动点的移动轨迹

len = 100
x = np.arange(0, len)
y = x

创建画布,设置画布宽度,高度(依照坐标值设定)

len = 100
fig = plt.figure()
plt.xlim(-1,len+1)
plt.ylim(-1,len+1)

创建动点的artist对象,初始的坐标在0下标,这个对象待会将会被animation更新,值得注意的是,逗号不能被省略,因为animation需要的是一个artist的序列

p, = plt.plot(x[0], y[0], "o")

编写初始化 / 更新函数,这里初始化就是设置0下标的坐标,更新函数则是接收传入的帧序列,更新点的坐标,返回要更新的artist对象序列,逗号同样不能省略

def update(frame):
    print(frame)
    p.set_data((x[frame]+1)%len, (y[frame]+1)%len)
    return p,

def init():
    p.set_data(x[0], y[0])
    return  p,

创建animation对象,以及调用animation对象的保存方法,我们可以生成一个动画

ani = animation.FuncAnimation(fig=fig, 
							  func=update, 
							  init_func=init,  
							  frames=np.arange(0, len), 
							  interval=10)
plt.show()
ani.save('1.gif', fps=30)

在这里插入图片描述

完整代码

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

if __name__ == '__main__':
    len = 100
    x = np.arange(0, len)
    y = x

    fig = plt.figure()
    plt.xlim(-1,len+1)
    plt.ylim(-1,len+1)
    p, = plt.plot(x[0], y[0], "o")

    def update(frame):
        print(frame)
        p.set_data((x[frame]+1)%len, (y[frame]+1)%len)
        return p,

    def init():
        p.set_data(x[0], y[0])
        return  p,

    ani = animation.FuncAnimation(fig=fig, func=update, init_func=init,  frames=np.arange(0, len), interval=10)
    plt.show()
    ani.save('1.gif', fps=30)
发布了262 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44176696/article/details/105348448