import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.sans-serif'] = 'SimHei'
# 准备数据
x= np.linspace(0,3*np.pi,100)
y1= np.sin(x)
y2= np.cos(x)
#创建画布和子图
fig,ax=plt.subplots(dpi=50)
#画出两条线
line1,= ax.plot(x,y1,ls='--')
line2,=ax.plot(x,y2,ls='-.',c='crimson')
#帧函数
def update(i,line):#更新数据
print(i)
line1.set_data(x[:i],y1[:i])
line2.set_data(x[:i],y2[:i])
return line1,line2,
#动画生产
def animate():
ani=FuncAnimation(fig=fig,
func=update,
fargs=((line2,)),
interval=500,
frames=len(x),
blit=True,
# repeat=False
)
plt.show()
添加图列,创建图列对象,然后用句柄函数handles添加即可。
#设置图列
plt.title("正余弦函数赛跑")
from matplotlib.lines import Line2D
sinLine=Line2D([0,1],[1,1],lw=3,ls=':',c='cornflowerblue',label=r'$y=\sin(x)$')#对象
cosLine=Line2D([0,1],[1,1],lw=3,ls='-.',c='crimson',label=r'$y=\cos(x)$') #对象
#添加到图列
plt.legend(handles=[sinLine,cosLine],ncol=2,loc='upper right')
保存动画用ani.save('001.gif')如果想背景透明,把子图设置
plt.axis('off') #关闭坐标轴
ax.patch.set_facecolor('none') #子画布对象设置透明
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.sans-serif'] = 'SimHei'
# 准备数据
x= np.linspace(0,3*np.pi,100)
y1= np.sin(x)
y2= np.cos(x)
#创建画布和子图
fig,ax=plt.subplots(dpi=100,facecolor='none')
#画出两条线
line1,= ax.plot(x,y1,ls=':',lw=4)
line2,=ax.plot(x,y2,ls='-.',c='crimson')
print(type(line1))
print(line1.__dict__)
#帧函数
def update(i,line):#更新数据
print(i)
line1.set_data(x[:i],y1[:i])
line2.set_data(x[:i],y2[:i])
return line1,line2,
#动画生产
def animate():
ani=FuncAnimation(fig=fig,
func=update,
fargs=((line2,)),
interval=500,
frames=len(x),
blit=True,
# repeat=False
)
#设置图列
plt.title("正余弦函数赛跑")
plt.axis('off') #关闭坐标轴
# ax.patch.set_facecolor('none') #子画布对象设置透明
from matplotlib.lines import Line2D
sinLine=Line2D([0,1],[1,1],lw=3,ls=':',c='cornflowerblue',label=r'$y=\sin(x)$')#对象
cosLine=Line2D([0,1],[1,1],lw=3,ls='-.',c='crimson',label=r'$y=\cos(x)$') #对象
#添加到图列
plt.legend(handles=[sinLine,cosLine],ncol=2,loc='upper right')
ani.save('sinsin.gif')
plt.show()
if __name__=='__main__':
animate()