Matplotlib animation模块实现动态图
matplotlib画图功能非常强大,目前也只能根据官网提供的例子简单地画几张图。最近学习了能画动态图的animation模块,作个简单地记录。
在matplotlib作图中,比较常用的是matplotlib.pyplot模块,这个模块有非常多的属性和方法,简要列举下这次用到的方法:
matplotlib.pyplot.subplots(nrows=1,ncols=1,sharex=False,sharey=False,squeeze=True,subplot_kw=None,gridspec_kw=None,**fig_kw)
返回fig和ax对象!
例子1.动态画出sin函数曲线
importnumpyasnp importmatplotlib.pyplotasplt frommatplotlib.animationimportFuncAnimation fig,ax=plt.subplots() xdata,ydata=[],[] ln,=ax.plot([],[],'r-',animated=False) definit(): ax.set_xlim(0,2*np.pi) ax.set_ylim(-1,1) returnln, defupdate(frame): xdata.append(frame) ydata.append(np.sin(frame)) ln.set_data(xdata,ydata) returnln, ani=FuncAnimation(fig,update,frames=np.linspace(0,2*np.pi,128), init_func=init,blit=True) plt.show()
画这类图的关键是要给出不断更新的函数,这里就是update函数了。注意,line,=ax.plot([],[],'r-',animated=False)中的,表示创建tuple类型。迭代更新的数据frame取值从frames取得。
例子2.动态显示一个动点,它的轨迹是sin函数。
importnumpyasnp importmatplotlib.pyplotasplt frommatplotlibimportanimation """ animationexample2 author:Kiterun """ fig,ax=plt.subplots() x=np.linspace(0,2*np.pi,200) y=np.sin(x) l=ax.plot(x,y) dot,=ax.plot([],[],'ro') definit(): ax.set_xlim(0,2*np.pi) ax.set_ylim(-1,1) returnl defgen_dot(): foriinnp.linspace(0,2*np.pi,200): newdot=[i,np.sin(i)] yieldnewdot defupdate_dot(newd): dot.set_data(newd[0],newd[1]) returndot, ani=animation.FuncAnimation(fig,update_dot,frames=gen_dot,interval=100,init_func=init) ani.save('sin_dot.gif',writer='imagemagick',fps=30) plt.show()
这里我们把生成的动态图保存为gif图片,前提要预先安装imagemagic。
例子3.单摆(没阻尼&有阻尼)
无阻尼的单摆力学公式:
附加阻尼项:
这里需要用到scipy.integrate的odeint模块,具体用法找时间再专门写一篇blog吧,动态图代码如下:
#-*-coding:utf-8-*- frommathimportsin,cos importnumpyasnp fromscipy.integrateimportodeint importmatplotlib.pyplotasplt importmatplotlib.animationasanimation g=9.8 leng=1.0 b_const=0.2 #nodecaycase: defpendulum_equations1(w,t,l): th,v=w dth=v dv=-g/l*sin(th) returndth,dv #thedecayexistcase: defpendulum_equations2(w,t,l,b): th,v=w dth=v dv=-b/l*v-g/l*sin(th) returndth,dv t=np.arange(0,20,0.1) track=odeint(pendulum_equations1,(1.0,0),t,args=(leng,)) #track=odeint(pendulum_equations2,(1.0,0),t,args=(leng,b_const)) xdata=[leng*sin(track[i,0])foriinrange(len(track))] ydata=[-leng*cos(track[i,0])foriinrange(len(track))] fig,ax=plt.subplots() ax.grid() line,=ax.plot([],[],'o-',lw=2) time_template='time=%.1fs' time_text=ax.text(0.05,0.9,'',transform=ax.transAxes) definit(): ax.set_xlim(-2,2) ax.set_ylim(-2,2) time_text.set_text('') returnline,time_text defupdate(i): newx=[0,xdata[i]] newy=[0,ydata[i]] line.set_data(newx,newy) time_text.set_text(time_template%(0.1*i)) returnline,time_text ani=animation.FuncAnimation(fig,update,range(1,len(xdata)),init_func=init,interval=50) #ani.save('single_pendulum_decay.gif',writer='imagemagick',fps=100) ani.save('single_pendulum_nodecay.gif',writer='imagemagick',fps=100) plt.show()
例子4.滚动的球
importnumpyasnp importmatplotlib.pyplotasplt importmatplotlib.animationasanimation fig=plt.figure(figsize=(6,6)) ax=plt.gca() ax.grid() ln1,=ax.plot([],[],'-',lw=2) ln2,=ax.plot([],[],'-',color='r',lw=2) theta=np.linspace(0,2*np.pi,100) r_out=1 r_in=0.5 definit(): ax.set_xlim(-2,2) ax.set_ylim(-2,2) x_out=[r_out*np.cos(theta[i])foriinrange(len(theta))] y_out=[r_out*np.sin(theta[i])foriinrange(len(theta))] ln1.set_data(x_out,y_out) returnln1, defupdate(i): x_in=[(r_out-r_in)*np.cos(theta[i])+r_in*np.cos(theta[j])forjinrange(len(theta))] y_in=[(r_out-r_in)*np.sin(theta[i])+r_in*np.sin(theta[j])forjinrange(len(theta))] ln2.set_data(x_in,y_in) returnln2, ani=animation.FuncAnimation(fig,update,range(len(theta)),init_func=init,interval=30) ani.save('roll.gif',writer='imagemagick',fps=100) plt.show()
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。