zl程序教程

您现在的位置是:首页 >  后端

当前栏目

matplotlib--animation

matplotlib -- animation
2023-09-14 09:13:09 时间
'''
Author: 365JHWZGo
Description: matplotlib--animation
Date: 2021/11/5 21:45
FilePath: day1105-6.py
'''
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

fig,ax = plt.subplots()
x = np.arange(0,2*np.pi,0.01)
line, = ax.plot(x,np.sin(x))    #加,是因为ax.plot()返回的是一个列表

#自定义动画函数
def animate(i):
    line.set_ydata(np.sin(x+i/10.0))
    return line,

def init():
    line.set_ydata(np.sin(x))
    return line,

ani = animation.FuncAnimation(
    fig=fig,
    func=animate,
    init_func=init,
    frames=100,
    interval=20,
    blit=False  #blit用于是否更新全部的数据,False表示只更新有变化的点
)
plt.show()

在这里插入图片描述

学习到了,那么我们来自己搞一个

'''
Author: 365JHWZGo
Description: matplotlib--animation2
Date: 2021/11/6 22:30
FilePath: day1106-2.py
'''

首先画一个静态的圆

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

# 圆心坐标
a, b = (0., 0.)
# 初始圆半径
r = 1
#圆心角θ
theta = np.linspace(0, 2 * np.pi, 200)

#绘制figure
fig, ax = plt.subplots(figsize=(3, 3))

x = a + r * np.cos(theta)
y = b + r * np.sin(theta)

circle, = ax.plot(x, y, color='red', linewidth=2)
ax.set_xticks(())
ax.set_yticks(())

plt.show()

在这里插入图片描述

使用刚刚学到的技能让它动起来吧!

'''
Author: 365JHWZGo
Description: matplotlib--animation2
Date: 2021/11/6 22:30
FilePath: day1106-2.py
'''

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

# 圆心坐标
a, b = (0., 0.)
# 初始圆半径
r = 1
theta = np.linspace(0, 2 * np.pi, 200)
fig, ax = plt.subplots(figsize=(3, 3))

x = a + r * np.cos(theta)
y = b + r * np.sin(theta)

circle, = ax.plot(x, y, color='red', linewidth=2)
ax.set_xticks(())
ax.set_yticks(())

def animate(i):
    circle.set_xdata(a + r * (i / 50.0) * np.cos(theta))	#主要的目的就是使其的半径发生变化
    circle.set_ydata(b + r * (i / 50.0) * np.sin(theta))
    return circle,

def init():
    circle.set_ydata(y)
    circle.set_xdata(x)
    return circle,

ani = animation.FuncAnimation(
    fig = fig,
    func=animate,
    init_func=init,
    frames=100,
    interval=10,
    blit=False
)
#plt.rcParams['animation.convert_path']='E:\ImageMagick-7.1.0-Q16-HDRI\magick.exe'
ani.save('circle.gif',writer='imagemagick')
plt.show()

在这里插入图片描述
一个圆的动画就已经生成了!