matplotlib动画入门(2):第一个动画
- 2019 年 10 月 6 日
- 筆記
新建一个文件 basic_animation.py,代码如下
源代码来源 https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/
''' 引入相应包 ''' import numpy as np from matplotlib import pyplot as plt from matplotlib import animation #创建一个Figure fig = plt.figure() #创建坐标,横坐标显示的区间是(0,2),纵坐标显示的空间是(-2,2) ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) #创建一个图(plot),初始横坐标纵坐标都是空,linewidth=2 line, = ax.plot([], [], lw=2) #初始化函数,会被FuncAnimation调用 def init(): line.set_data([], []) return line, # 动画函数,每一帧都会调用此函数,i为帧号. def animate(i): #返回一个ndarray数组,起始为0,终止为2,100个元素。 x = np.linspace(0, 2, 100) #计算y值 y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, ''' 执行动画 fig: call the animator. blit=True means only re-draw the parts that have changed. ''' anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) plt.show()
执行代码
python3 basic_animation.py